[LeetCode] 2441. Largest Positive Integer That Exists With Its Negative

Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array.

Return the positive integer k. If there is no such integer, return -1.

Example 1:
Input: nums = [-1,2,-3,3]
Output: 3
Explanation: 3 is the only valid k we can find in the array.

Example 2:
Input: nums = [-1,10,6,7,-7,1]
Output: 7
Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.

Example 3:
Input: nums = [-10,8,6,7,-2,-3]
Output: -1
Explanation: There is no a single valid k, we return -1.

Constraints:
1 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
nums[i] != 0

与对应负数同时存在的最大正整数。

给你一个 不包含 任何零的整数数组 nums ,找出自身与对应的负数都在数组中存在的最大正整数 k 。

返回正整数 k ,如果不存在这样的整数,返回 -1 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/largest-positive-integer-that-exists-with-its-negative
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路 - 扫描一遍

思路是 hashset。我们需要创建一个变量 res,初始值为 -1。然后遍历 input 数组,在遍历的过程中,将每个数字放入 hashset 并判断当前数字对应的负数是否已经存在于 hashset 了,如果存在,则当前数字的绝对值可以用来更新 res。

复杂度

时间O(n)
空间O(n)

代码

Java实现

class Solution {
    public int findMaxK(int[] nums) {
        Set<Integer> set = new HashSet<>();
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        int res = -1;
        for (int num : nums) {
            set.add(num);
            if (set.contains(-num) && Math.abs(num) > max) {
                res = Math.abs(num);
                max = Math.abs(num);
            }
        }
        return res;
    }
}
posted @ 2023-05-13 02:23  CNoodle  阅读(72)  评论(0)    收藏  举报