標籤:沒有 alt etc list col 複雜度 就是 演算法 題解
探討一下leetcode上的3Sum:
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: 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]]
1.暴力解法
時間複雜度高達O(n^3)
public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> lists =new ArrayList<List<Integer>>(); for(int i=0;i<nums.length-2;i++) { for (int j = i + 1; j < nums.length-1; j++) { for(int z=j+1;z<nums.length;z++){ if(nums[i]+nums[j]+nums[z]==0){ List<Integer> list =new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[z]); lists.add(list); } } } } return lists; }
運行結果:
結果不盡人意,有個重複的。我想過如果使用list排重的話。必然先要對list進行排序,然後對比是否相等,如果相等,再剔除掉一樣的。代碼如下:
public static List<List<Integer>> three(int[] nums){ List<List<Integer>> lists =new ArrayList<List<Integer>>(); for(int i=0;i<nums.length-2;i++) { for (int j = i + 1; j < nums.length-1; j++) { for(int z=j+1;z<nums.length;z++){ if(nums[i]+nums[j]+nums[z]==0){ List<Integer> list =new ArrayList<Integer>();
boolean flag = true; list.add(nums[i]); list.add(nums[j]); list.add(nums[z]); Collections.sort(list); for(int k=0;i<lists.size();i++){ if(list.equals(lists.get(i))){ flag = false; } }
if(flag){ lists.add(list);
} } } } } return lists; }
運行結果:
看著貌似問題解決了,但是Runtime=2ms,時間有點長,時間複雜度太高了。
上交的時候爆出來一個錯誤:
既然結果都能運行出來,為什麼還爆數組越界呢?我也看不出來什麼毛病。
2.使用map
時間複雜度為O(n+n^2),即O(n^2)
public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> lists =new ArrayList<List<Integer>>(); Map<Integer,Integer> map =new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ map.put(nums[i],i); } for(int i=0;i<nums.length;i++){ for(int j=i+1;j<nums.length;j++) { int res=0-nums[i]-nums[j]; if(map.containsKey(res)&&map.get(res)!=i&&map.get(res)!=j){ List<Integer> list =new ArrayList<Integer>(); list.add(res); list.add(nums[i]); list.add(nums[j]); lists.add(list); } } } return lists; }
這個的運行結果讓人頭疼。
有沒有好的辦法可以排重,如果這樣的話:
public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> lists =new ArrayList<List<Integer>>(); Map<Integer,Integer> map =new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ for(int j=i+1;j<nums.length;j++) { int res=0-nums[i]-nums[j]; if(map.containsKey(res)){ List<Integer> list =new ArrayList<Integer>(); list.add(res); list.add(nums[i]); list.add(nums[j]); lists.add(list); } } map.put(nums[i],i); } return lists; }
運行結果:
這下結果正確了,提交一下:
對於上面的數組,演算法是不成立的。我把上面的list排重寫進裡面,但是就是解決不了問題。請高手幫我解決問題,共同學習。
附上leetcode這個問題的地址:
15. 3Sum
3Sum探討(Java)