LeetCode 15. 三數之和(C、C++、python)
阿新 • • 發佈:2018-12-16
給定一個包含 n 個整數的陣列 nums
,判斷 nums
中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。
例如, 給定陣列 nums = [-1, 0, 1, 2, -1, -4], 滿足要求的三元組集合為: [ [-1, 0, 1], [-1, -1, 2] ]
C
/** * Return an array of arrays of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int** threeSum(int* nums, int numsSize, int* returnSize) { int n=numsSize; int** res=(int**)malloc(sizeof(int*)*(n*10)); for(int i=0;i<(n*10);i++) { res[i]=(int*)malloc(sizeof(int)*3); } if(n<3) { *returnSize=0; return res; } int s=0; sort(nums,0,n-1); for(int i=0;i<=n-3;i++) { int j=i+1; int k=n-1; int m=0-nums[i]; while(j<k) { int sum=nums[j]+nums[k]; if(m==sum) { res[s][0]=nums[i]; res[s][1]=nums[j++]; res[s][2]=nums[k--]; s++; while(j<k && nums[j]==nums[j-1]) { j++; } while(j<k && nums[k]==nums[k+1]) { k--; } } else if(sum>m) { k--; } else { j++; } } while(i<=n-3 && nums[i]==nums[i+1]) { i++; } } *returnSize=s; return res; } void sort(int *a, int left, int right) { if(left >= right) { return ; } int i = left; int j = right; int key = a[i]; while(i < j) { while(i < j && key <= a[j]) { j--; } a[i] = a[j]; while(i < j && key >= a[i]) { i++; } a[j] = a[i]; } a[i] = key; sort(a, left, i - 1); sort(a, i + 1, right); }
C++
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { int n=nums.size(); vector<vector<int>> res; vector<int> tmp(3); if(n<3) { return res; } sort(nums.begin(),nums.end()); for(int i=0;i<=n-3;i++) { int j=i+1; int k=n-1; int m=0-nums[i]; while(j<k) { int sum=nums[j]+nums[k]; if(m==sum) { tmp[0]=nums[i]; tmp[1]=nums[j++]; tmp[2]=nums[k--]; res.push_back(tmp); while(j<k && nums[j]==nums[j-1]) { j++; } while(j<k && nums[k]==nums[k+1]) { k--; } } else if(sum>m) { k--; } else { j++; } } while(i<=n-3 && nums[i]==nums[i+1]) { i++; } } return res; } };
python
class Solution: def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ n=len(nums) if n<3: return [] nums.sort() res=[] tmp=[0 for i in range(3)] #for i in range(0,n-2): i=0 while i<=n-3: m=0-nums[i] j=i+1 k=n-1 while j<k: su=nums[j]+nums[k] if su==m: res.append([nums[i],nums[j],nums[k]]) j+=1 k-=1 while j<k and nums[j]==nums[j-1]: j+=1 while j<k and nums[k]==nums[k+1]: k-=1 elif su>m: k-=1 else: j+=1 while i<=n-3 and nums[i]==nums[i+1]: i+=1 i+=1 return res