首页 > 编程语言 > 详细

15. 3Sum(C++)

时间:2017-03-03 22:43:04      阅读:285      评论:0      收藏:0      [点我收藏+]

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: 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]
]

 

solution :

class Solution {
public:
  vector<vector<int>> threeSum(vector<int>& nums) {
    int len=nums.size();
    vector<vector<int>> solution;//(m);
    std::sort(nums.begin(),nums.end());
    for(int i=0;i<len;i++){
      int sum=-nums[i];
      int left=i+1;
      int right=len-1;
      while(left<right){
        int number=nums[left]+nums[right];
        if(sum>number){
          left++;
        }else if(sum<number){
          right--;
        }else{
          vector<int> tmp(3,0);
          tmp[0]=nums[i];
          tmp[1]=nums[left];
          tmp[2]=nums[right];
          solution.push_back(tmp);
          while(left<right && nums[left]==tmp[1]) left++;
          while(left<right && nums[right]==tmp[2]) right--;
        }
      }
      while(i+1<len && nums[i]==nums[i+1]) i++;
    }
    return solution;
  }
};




15. 3Sum(C++)

原文:http://www.cnblogs.com/devin-guwz/p/6498574.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!