leetcode 015 —— 3Sum

来源:互联网 发布:淘宝买东西好评怎么写 编辑:程序博客网 时间:2024/06/05 07:05

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++;elseend--;}}return res;}};


0 0