- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1099.java
47 lines (44 loc) · 1.35 KB
/
_1099.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
packagecom.fishercoder.solutions.secondthousand;
importjava.util.Arrays;
publicclass_1099 {
publicstaticclassSolution1 {
/*
* Time: O(n^2)
* Space: O(1)
*/
publicinttwoSumLessThanK(int[] nums, intk) {
intmaxSum = Integer.MIN_VALUE;
for (inti = 0; i < nums.length - 1; i++) {
for (intj = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] < k) {
maxSum = Math.max(maxSum, nums[i] + nums[j]);
}
}
}
returnmaxSum == Integer.MIN_VALUE ? -1 : maxSum;
}
}
publicstaticclassSolution2 {
/*
* Time: O(nlogn)
* Space: O(1)
*/
publicinttwoSumLessThanK(int[] nums, intk) {
Arrays.sort(nums);
intleft = 0;
intright = nums.length - 1;
intsum = Integer.MIN_VALUE;
while (left < right) {
intnewSum = nums[left] + nums[right];
if (newSum < k && newSum > sum) {
sum = newSum;
} elseif (newSum >= k) {
right--;
} else {
left++;
}
}
returnsum == Integer.MIN_VALUE ? -1 : sum;
}
}
}