Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0f3d16c

Browse files
MEDIUM/src/medium/_3Sum.java
1 parent1fd7d00 commit0f3d16c

File tree

1 file changed

+24
-17
lines changed

1 file changed

+24
-17
lines changed

‎MEDIUM/src/medium/_3Sum.java

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,34 @@
55
importjava.util.List;
66

77
publicclass_3Sum {
8-
8+
/**This solution is pretty clear and similar to my own thought:
9+
* https://discuss.leetcode.com/topic/26050/simple-o-n-2-two-pointers-java-solution*/
10+
11+
/**ATTN: this two-pointer technique here doesn't need a middle pointer!!! Instead, we just increment/decrement left
12+
* or right pointer by 1 each time when the sum != 0*/
913
publicList<List<Integer>>threeSum(int[]nums) {
10-
Arrays.sort(nums);
1114
List<List<Integer>>result =newArrayList();
12-
intleft =0,right =nums.length-1,mid =0;
13-
while(left+1 <right){
14-
mid =left + (right-left)/2;
15-
intsum =nums[left] +nums[mid] +nums[right];
16-
if(sum ==0){
17-
List<Integer>list =newArrayList();
18-
list.add(nums[left]);
19-
list.add(nums[mid]);
20-
list.add(nums[right]);
21-
22-
//move left forward to get all possible combinations
23-
}elseif(sum >0){
24-
right =mid;
25-
}else {
26-
left =mid;
15+
if(nums ==null ||nums.length ==0)returnresult;
16+
Arrays.sort(nums);//you'll have to sort it first, this is very important and very natural to think of
17+
for(inti =0;i <nums.length;i++){//we can let i reach the last element, it's fine since we have other checks afterwards, it won't go out of bound exception.
18+
if(i >=1 &&nums[i] ==nums[i-1])continue;//skip equal elements to avoid duplicates
19+
intleft =i+1,right =nums.length-1;
20+
while(left <right){
21+
intsum =nums[i] +nums[left] +nums[right];
22+
if(sum ==0){
23+
result.add(Arrays.asList(nums[i],nums[left],nums[right]));
24+
while(left +1 <right &&nums[left] ==nums[left+1])left++;
25+
while(right -1 >left &&nums[right] ==nums[right-1])right--;
26+
left++;//be sure to have these two lines after the above two while loops
27+
right--;
28+
}elseif(sum <0){
29+
left++;
30+
}else {
31+
right--;
32+
}
2733
}
2834
}
35+
returnresult;
2936
}
3037

3138
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp