標籤:des style blog http color os strong io
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
題解:把3Sum轉換成2Sum,然後解決2Sum問題。
對於num中任意一個數num[i],我們要在i+1~num.length-1之間尋找兩個數使得它們的和為0-num[i]。
而尋找兩個數使得它們的和為0-num[i],我們可以設定兩個指標start和last,我們知道在start+1~last之間我們要尋找的數是0-num[i]-num[start],這樣三個數的和就是0了。所以如果
- last所指向的數比0-num[i]-num[start]大,我們把last指標往前移動;
- 如果比0-num[i]-num[start]小,我們把start指標往後移動(last指標不動是因為我們已經搜尋過了可能和last指標後面組成答案的數,這些數在start之前);
- 如果相等,就把num[i],num[start]和num[last]三個數依次放在list中作為一組答案。然後越過start後面和start相等的數,繼續迴圈。
圖示如下:
例如題目的數組排序後得到{-4,-1,0,1,2},當i指向-1的時候,我們需要在{0,1,2}之中找到兩個數和為0-(-1)=1,把start指向0,last指向2,那麼我們接下來要利用last找到1,last目前指向2,比需要的數1大,所以前移last,wala,我們找到了需要的1,同時找到了一組答案[-1,0,1]。
去重的工作十分簡單,除了上述說的越過start後面和start相等的數外,在最外層的for迴圈的時候,如果num[i] = num[i-1],那麼也可以越過i。
最後代碼如下:
1 public class Solution { 2 public List<List<Integer>> threeSum(int[] num) { 3 List<List<Integer>> answer = new ArrayList<List<Integer>>(); 4 if(num == null || num.length == 0) 5 return answer; 6 Arrays.sort(num); 7 8 for(int i = 0;i < num.length;i++){ 9 //remove duplicates10 if(i != 0 && num[i] == num[i-1])11 continue;12 int twoSum = 0 - num[i];13 int start = i + 1;14 int last = num.length-1;15 while(start < last){16 int OneSum = twoSum - num[start];17 //Found one solution18 if(num[last] == OneSum){19 ArrayList<Integer> result = new ArrayList<Integer>();20 result.add(num[i]);21 result.add(num[start]);22 result.add(num[last]);23 answer.add(result);24 start++;25 last--;26 //remove duplicates27 while(start < last && num[start] == num[start-1])28 start++;29 }30 else if(num[last] > OneSum)31 {32 last--; 33 }34 else{35 start++;36 }37 }38 }39 40 return answer;41 }42 }