leetcode之3Sum

原題如下:

Given an array S of n integers, are there elements abc 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)
經過昨天的搜狗面試,我更加註意算法的時間複雜度問題,顯然這道題存在暴力解法,其複雜度爲O(n*n*n),現在考慮的是降低複雜度的問題,首先進行排序,其時間複雜度爲O(nlogn),然後當爲2Sum問題時可以採用左右指針查找的方法(這裏因爲數組中存在重複元素,所以需要去重),此時查找複雜度爲O(n),所以總的時間複雜度爲O(nlogn),在求解3Sum問題時,首先選中一個元素,然後在剩餘的元素中進行2Sum的查找,此時總的時間複雜度爲O(n*n),這裏需要注意的仍是去重問題,首先選擇第一個元素時需要去重,接下來在左右指針移動過程中仍要去重。

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
		sort(num.begin(),num.end());
		vector<vector<int>>vv;
		if(num.size() < 3)
			return vv;
		for(int i = 0; i < num.size() - 2; i++){
			if(i > 0 && num[i] == num[i - 1])
				continue;
			twoSum(vv,num,i + 1,num[i] * -1);
		}
		return vv;
    }
	void twoSum(vector<vector<int>>&vv,vector<int>num,int index,int target){
		int left = index,right = num.size() - 1;
		while(left < right){
			int temp = num[left] + num[right];
			if(temp == target ){
			    vector<int>triplet;
				triplet.push_back(target * -1);
				triplet.push_back(num[left]);
				triplet.push_back(num[right]);				
				vv.push_back(triplet);
				left++;
				right--;
				while ( left < num.size() && num[left] == num[left - 1] )
					left++;
				while( right >= 0 && num[right] == num[right + 1])
					right--;
			}
			else if(temp > target){
			    right--;
			}
			else
				left++;
		}
	}
};


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