leetcode第15題——**3Sum
阿新 • • 發佈:2019-01-24
題目
Given an array S of n integers, are there elements a,b,c inS 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)
思路
這是Ksum類的問題,求出陣列中K個數滿足和為target的值。這一類問題都有類似解法。
可以先把陣列非遞減排序,然後從頭到尾遍歷陣列,每次固定一個數nums[a],然後就是從剩下的數當中找到和為-nums[a]的兩個數,由於陣列是有序的,可以從頭尾分別往中間靠攏,這樣找兩個和為-nums[a]的時間複雜度為o(n)
排序的時間複雜度為O(nlgn),找出資料並去重的時間複雜度為O(n^2),整體時間複雜度為O(nlgn)+O(n^2),當n很大時時間複雜度為O(n^2)
程式碼
Python
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ leng = len(nums) res = [] if (nums == None or leng < 3): return res nums.sort() for a in xrange(leng): #去重 if (a > 0 and nums[a] == nums[a-1]): continue b = a + 1; c = leng - 1; while(b < c): tsum = nums[a] + nums[b] + nums[c] if (tsum < 0): #頭指標往前移動 b += 1 elif (tsum > 0): #尾指標往後移動 c -= 1 else: item = [] item.append(nums[a]) item.append(nums[b]) item.append(nums[c]) res.append(item) #如果有相等數字,則頭尾指標要移動(去重) while(True): b += 1 if (b < c and nums[b-1] == nums[b]): continue else: break while(True): c -= 1 if (c > b and nums[c+1] == nums[c]): continue else: break return res
Java
public class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if (nums == null || nums.length < 3) return res; //先對陣列排序 Arrays.sort(nums); int len = nums.length; int a,b,c,sum; for(a = 0; a < len; a++){ //去重 if(a > 0 && nums[a] == nums[a-1]) continue; b = a + 1; c = len - 1; while(b < c){ sum = nums[a] + nums[b] + nums[c]; if(sum < 0) b++;//如果sum太小,頭指標往後移動,找更大的數 else if(sum > 0) c--;//如果sum太大,尾指標往前移動 else{ List<Integer> item = new ArrayList<Integer>(); item.add(nums[a]); item.add(nums[b]); item.add(nums[c]); res.add(item); while((b+=1) < c && nums[b-1] == nums[b]){ continue; } while((c-=1) > b && nums[c+1] == nums[c]){ continue; } } } } return res; } }