Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/2441.html
2441. Largest Positive Integer That Exists With Its Negative
- Difficulty: Easy.
- Related Topics: .
- Similar Questions: .
Problem
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
Solution (Java, C++, Python)
-
class Solution { public int findMaxK(int[] nums) { int ans = -1; Set<Integer> s = new HashSet<>(); for (int v : nums) { s.add(v); } for (int v : s) { if (s.contains(-v)) { ans = Math.max(ans, v); } } return ans; } }
-
class Solution { public: int findMaxK(vector<int>& nums) { unordered_set<int> s(nums.begin(), nums.end()); int ans = -1; for (int& v : nums) { if (s.count(-v)) { ans = max(ans, v); } } return ans; } };
-
class Solution: def findMaxK(self, nums: List[int]) -> int: ans = -1 s = set(nums) for v in s: if -v in s: ans = max(ans, v) return ans
-
func findMaxK(nums []int) int { s := map[int]bool{} for _, v := range nums { s[v] = true } ans := -1 for v := range s { if s[-v] && ans < v { ans = v } } return ans }
-
function findMaxK(nums: number[]): number { const set = new Set(nums); let res = -1; for (const num of set) { if (set.has(-num)) { res = Math.max(num, res); } } return res; }
-
use std::collections::HashSet; impl Solution { pub fn find_max_k(nums: Vec<i32>) -> i32 { let set = nums.into_iter().collect::<HashSet<i32>>(); let mut res = -1; for &num in set.iter() { if set.contains(&(-num)) { res = res.max(num); } } res } }
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).