LeetCoder 解題報告 3Sum
阿新 • • 發佈:2019-02-08
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)
分析:在 LeetCode 解題報告 Two Sum 這篇文章中介紹了三種方法,此題是這個題的升級版,這個題如果用暴力解決那麼將是O(n3)的時間複雜度,如果用HashMap也是不方便,因為資料是可重複的。
接下來就直接看程式碼
public List<List<Integer>> threeSum(int[] num) { Arrays.sort(num); List<List<Integer>> list = new ArrayList<List<Integer>> (); int first, end, mid; //遍歷陣列 for(int i = 0; i < num.length-2; i++) { if(i==0 || num[i] > num[i-1]) { first = i; end = num.length - 1; mid = first + 1; if(num[first] > 0 || num[end] < 0) break; while(mid < end) { int sum = num[first] + num[mid] + num[end]; if(sum == 0) { ArrayList<Integer> each = new ArrayList<Integer>(); each.add(num[first]); each.add(num[mid]); each.add(num[end]); if(!list.contains(each)) list.add(each); mid++; end--; while(mid < end && num[end] == num[end-1]) end--; while(mid < end && num[mid] == num[mid+1]) mid ++; } else if(sum < 0) { mid++; } else end--; } } } return list; }
思路其實就很簡單了,就是鎖定第一個值遍歷,剩下的兩個的數,按照陣列中尋找兩個數的和是定值來解決就ok了。
如果按著思路寫出的程式碼提交會有出現超時現象,那麼我們就要優化了。
這裡面做了很多的優化,比如:if(i==0 || num[i] > num[i-1])
這裡是防止相同資料輸入
這裡避免不必要的重複while(mid < end && num[end] == num[end-1]) end--; while(mid < end && num[mid] == num[mid+1]) mid ++;