leetcode:三數之和

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
 一個是暴力求解,三層循環,複雜度是三次方O(n3),太耗時。另一種,利用兩數之和的求解方法,拆爲一個數,和兩個數,兩數之和是0-num1,
再按兩數求解的方式,另外要求不能重複,就用set來存儲,最後給vector,若嫌代價大,那就自己檢測,但貌似未必比set來的有效率。
    vector<vector<int>> threeSum(vector<int>& nums) {
     set<vector<int>> result;
	 sort(nums.begin(), nums.end());
	 for(int i=0; i<nums.size();++i){
		if(nums[i]>0)
			break;
		if(k>0&&nums[i] == nums[i-1])
			contimue;
		int target=0-nums[i];
		int j=i+1;
		int k=nums.size()-1;
		while(j<k)
			if(num[j)+nums[k]==target){
				result.insert({nums[i],nums[j],nums[k]});
				++j;--k;
			}
			else if(nums[j]+nums[k]<target)
				++j;
			else
				--k;
	 }
	 return vector<vector<int>>(result.begin(),result.end());
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章