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

]

解题思路:首先对数组进行排序,然后对数组进行遍历,每次把第i个数作为定值,在i以后的有序数组中,寻找使得加上第i个数等于0的两个数;寻找的策略贪心,首尾相加判断是否等于0 - nums[i] ;等于的操作是首尾各自中间移一位;如果大于,尾部向中间移一位;如果小于,首部向中间移一位;接下来,我们就要考虑数字中重复数字,  不考虑重复的数字数组集合里面就会出现相同的数组;考虑重复,就必须考虑i重复,和i以后有序数列中连续重复的数字,但又因为,单个数组中可以出现重复的数字,所以不用考虑i 与i以后的有序数列是否重复;所以我们只要在i的遍历中,最要相同的i就后移,直到不同的i;而在i以后寻找两个数时,与0-nums[i]相等时,两端向中间移动也要考虑重复数字,同理 大于0-nums[i]时,尾端移动时也要去除重复的数字,小于也是;

class Solution {
public:
	vector<vector<int>> threeSum(vector<int>& nums) {
	    vector<vector<int>> rs;
		if(nums.size() < 2) return rs;
		vector<int> ls(3, 0);
		sort(nums.begin(),nums.end());
		int i,start,end,pt;
		int sum;
		for (i = 0; i < nums.size() - 2; i++) {
		   start = i + 1;end = nums.size() - 1;
		   pt = 0 - nums[i];
		   while(start < end){
		      sum = nums[start] + nums[end];
		      if (sum == pt){
		          ls[0] = nums[i];
		          ls[1] = nums[start];
		          ls[2] = nums[end];
		          rs.push_back(ls);
		          while(nums[start] == nums[start + 1] && start < end) start++;
		          while(nums[end] == nums[end - 1] && start < end)end--;
		          start++;end--;
		      }
		      if(sum > pt) {while(nums[end] == nums[end - 1] && start < end)end--;end--;}
		      if(sum < pt) {while(nums[start] == nums[start + 1] && start < end)start++;start ++;}
		   }
		   while(i + 1 < nums.size()&&nums[i] == nums[i+1]) i++;
		}
		return rs;
	}
};

运行结果:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值