Skip to content

Commit 8f0ed51

Browse files
easy map java two pointer 2441
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 Seen this question in a real interview before? 1/5 Yes No Accepted 189.4K Submissions 252.3K Acceptance Rate 75.1% Topics Array Hash Table Two Pointers Sorting Companies Hint 1 What data structure can help you to determine if an element exists? Hint 2 Would a hash table help?
1 parent 63fb7b6 commit 8f0ed51

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public int findMaxK(int[] nums) {
3+
int[] map=new int[1001];
4+
int max=-1;
5+
for(int i:nums){
6+
if(i<0)
7+
map[-i]=i;
8+
}
9+
for(int i : nums){
10+
if(i>0 && map[i]!=0)
11+
max=Math.max(max,i);
12+
}
13+
return max;
14+
}
15+
}
16+
17+
// Less opitimised solution beats 68%
18+
// class Solution {
19+
// public int findMaxK(int[] nums) {
20+
// Arrays.sort(nums);
21+
// int left=0;
22+
// int right=nums.length-1;
23+
// int maxk=0;
24+
// while(left<right){
25+
// int sum=nums[left]+nums[right];
26+
// if(sum==0){
27+
// maxk=Math.max(maxk,nums[right]);
28+
// left++;
29+
// right--;
30+
// }
31+
// else if(sum<0){
32+
// left++;
33+
// }
34+
// else right--;
35+
// }
36+
// if(maxk!=0){
37+
// return maxk;
38+
// }
39+
// else return -1;
40+
// }
41+
// }

0 commit comments

Comments
 (0)