Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 5a8f5ce

Browse files
add another solution for 1099
1 parent f3d09d7 commit 5a8f5ce

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/main/java/com/fishercoder/solutions/_1099.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.fishercoder.solutions;
22

3+
import java.util.Arrays;
4+
35
/**
46
* 1099. Two Sum Less Than K
57
*
@@ -26,6 +28,10 @@
2628
* */
2729
public class _1099 {
2830
public static class Solution1 {
31+
/**
32+
* Time: O(n^2)
33+
* Space: O(1)
34+
* */
2935
public int twoSumLessThanK(int[] A, int K) {
3036
int maxSum = Integer.MIN_VALUE;
3137
for (int i = 0; i < A.length - 1; i++) {
@@ -38,4 +44,28 @@ public int twoSumLessThanK(int[] A, int K) {
3844
return maxSum == Integer.MIN_VALUE ? -1 : maxSum;
3945
}
4046
}
47+
48+
public static class Solution2 {
49+
/**
50+
* Time: O(nlogn)
51+
* Space: O(1)
52+
* */
53+
public int twoSumLessThanK(int[] A, int K) {
54+
Arrays.sort(A);
55+
int left = 0;
56+
int right = A.length - 1;
57+
int sum = Integer.MIN_VALUE;
58+
while (left < right) {
59+
int newSum = A[left] + A[right];
60+
if (newSum < K && newSum > sum) {
61+
sum = newSum;
62+
} else if (newSum >= K) {
63+
right--;
64+
} else {
65+
left++;
66+
}
67+
}
68+
return sum == Integer.MIN_VALUE ? -1 : sum;
69+
}
70+
}
4171
}

src/test/java/com/fishercoder/_1099Test.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,12 @@
88

99
public class _1099Test {
1010
private static _1099.Solution1 solution1;
11+
private static _1099.Solution2 solution2;
1112

1213
@BeforeClass
1314
public static void setup() {
1415
solution1 = new _1099.Solution1();
16+
solution2 = new _1099.Solution2();
1517
}
1618

1719
@Test
@@ -24,4 +26,14 @@ public void test2() {
2426
assertEquals(-1, solution1.twoSumLessThanK(new int[]{10, 20, 30}, 15));
2527
}
2628

29+
@Test
30+
public void test3() {
31+
assertEquals(58, solution2.twoSumLessThanK(new int[]{34, 23, 1, 24, 75, 33, 54, 8}, 60));
32+
}
33+
34+
@Test
35+
public void test4() {
36+
assertEquals(-1, solution2.twoSumLessThanK(new int[]{10, 20, 30}, 15));
37+
}
38+
2739
}

0 commit comments

Comments
 (0)