LeetCode *** 15. 3Sum (Two Pointers )

来源:互联网 发布:销售类crm系统源码 编辑:程序博客网 时间:2024/05/06 07:55

题目:

Given an array S of n integers, are there elements a,b, c 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,abc)
  • 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;set<vector<int>> myrecord;int size = nums.size();sort(nums.begin(), nums.end());for (int i = 0; i<size - 2; ++i) {int j = i + 1, k = size - 1, tmp = nums[i];while (j<k) {if ((j == i + 1 || nums[j] != nums[j - 1]) && (k == size - 1 || nums[k] != nums[k + 1])) {if (tmp + nums[j] + nums[k] == 0) {vector<int> t = { nums[i] ,nums[j] ,nums[k] };if (myrecord.find(t) == myrecord.end()) {res.push_back(t);myrecord.insert(t);}j++; k--;}else if (tmp + nums[j] + nums[k]>0) {k--;}else j++;}if (k != size - 1 && nums[k] == nums[k + 1])k--;if (j != i + 1 && nums[j] == nums[j - 1])j++;}}return res;}};

0 0
原创粉丝点击