3Sum-Leetcode

Given an array S ofn 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: 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为数组第一个的值,pre为数组第二个的值,back为数组的第三个的值,主要是以向中靠拢的原则。
还有就是由于不是每个元素是独一的,要遍历相同的元素。

 
 
class Solution {
public:
	vector
    
    
     
     
      
      > threeSum(vector
      
      
       
       & nums) {
		vector
       
       
        
        
          > t; sort(nums.begin(), nums.end()); int len = nums.size(); for (int i = 0; i 
         
           x(3, 0); x[0] = nums[i]; x[1] = nums[pre]; x[2] = nums[back]; t.push_back(x); while (pre < back && nums[pre] == x[1]) pre++; //当对于i来说,第二个元素的值只能用一次 while (pre< back && nums[back] == x[2]) back--;//当对于i来说,第三个元素的值只能用一次 } else if (nums[i] + s2 > 0){ back--; } else if (nums[i] + s2 < 0){ pre++; } } while (i + 1 < len && nums[i + 1] == nums[i]) //第二个元素和第一个元素相同时,下回就不能将第二个元素当作第一个元素来遍历 i++; } return t; } }; 
          
        
       
       
      
      
     
     
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值