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

Commit 501f47d

Browse files
committed
Add Arrays/15_3Sum.java
1 parent 35fe0fa commit 501f47d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Arrays/15_3Sum.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public List<List<Integer>> threeSum(int[] nums) {
3+
List<List<Integer>> result = new ArrayList<>();
4+
5+
Arrays.sort(nums);
6+
7+
for (int i = 0; i < nums.length; i++) {
8+
if (i > 0 && nums[i] == nums[i - 1]) { continue; }
9+
10+
int j = i + 1, k = nums.length - 1;
11+
12+
while (j < k) {
13+
int sum = nums[i] + nums[j] + nums[k];
14+
15+
if (sum == 0) {
16+
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
17+
++j;
18+
19+
while (j < k && nums[j] == nums[j-1]) {
20+
++j;
21+
}
22+
} else if (sum > 0) {
23+
--k;
24+
} else {
25+
++j;
26+
}
27+
}
28+
}
29+
30+
return result;
31+
}
32+
}

0 commit comments

Comments
 (0)