File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ //015. 3Sum
2+ class Solution {
3+ public List <List <Integer >> threeSum (int [] nums ) {
4+ //create result list to store i,j,k
5+ List <List <Integer >> result = new LinkedList <List <Integer >>();
6+
7+ //sorting nums
8+ Arrays .sort (nums );
9+
10+ for (int i = 0 ; i < nums .length - 2 ; i ++) {
11+
12+ int left = i + 1 ;
13+ int right = nums .length - 1 ;
14+
15+ if (i > 0 && nums [i ] == nums [i -1 ]) {
16+ continue ; //if nums have same numbers, just check one time.
17+ }
18+
19+ while (left < right ) {
20+ int sum = nums [left ] + nums [right ] + nums [i ];
21+
22+ if (sum == 0 ) {
23+ //if sum == 0, store i,j,k
24+ result .add (Arrays .asList (nums [i ], nums [left ], nums [right ]));
25+ left ++; //check anoter case
26+ right --;
27+ //if next number == now number
28+ while (nums [left ] == nums [left - 1 ] && left < right ) {
29+ left ++;
30+ }
31+ while (nums [right ] == nums [right + 1 ] && left < right ) {
32+ right --;
33+ }
34+ } else if (sum > 0 ) {
35+ //if sum > 0, right--;
36+ right --;
37+ } else {
38+ //if sum < 0, left++;
39+ left ++;
40+ }
41+ }
42+ }
43+
44+ return result ; //return result list
45+ }
46+ }
47+
You can’t perform that action at this time.
0 commit comments