leetcode 015 —— 3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Fi
nd 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)

思路:排序,锁定一个节点,在后续节点中,双端扫描。

class Solution {
public:
	vector<vector<int>> threeSum(vector<int>& nums) {
		vector<vector<int>> res;
		int n = nums.size();
		if (n < 3)	return res;
		sort(nums.begin(), nums.end());
		for (int i = 0; i < n - 2; i++){
			if (i>0 && nums[i] == nums[i - 1])//序列nums是递增的,所以nums[i]能产生的组合总是<= nums[i-1]
				continue;
			int target = 0 - nums[i];
			int start = i+1;
			int end = n-1;
			while (start < end){
				int sum = nums[start] + nums[end];
				if (sum == target){
					vector<int> tmp;
					tmp.push_back(nums[i]);
					tmp.push_back(nums[start]);
					tmp.push_back(nums[end]);
					//cout << nums[i] << ' ' << nums[start] << ' ' << nums[end] << endl;
					res.push_back(tmp);
					while (start < end&&nums[start] == nums[start + 1])
						start++;
					while (start < end&&nums[end] == nums[end - 1])
						end--;
					start++;  //继续往中间搜索
					end--;

				}
				else if (sum < target)
					start++;
				else
					end--;
					
			}
			
		}
		return res;
		

	}
};


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

leetcode 015 —— 3Sum

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭