设为首页 加入收藏

TOP

LeetCode15:3Sum
2015-11-21 00:58:34 来源: 作者: 【 】 浏览:2
Tags:LeetCode15:3Sum

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, 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)

这道题可以用求两个数的和相同的解法来求解。需要注意的是对重复元素的处理,如果不加上这个减枝处理,在leetcode中会显示超时。
首先对数组进行排序,时间复杂度是O(Nlog(N))。
然后定义三个指针,第一个指针从头遍历到尾,第二个指针和第三个指针和求两个数的和时的那两个指针一样从两端开始遍历,左端由第一个指针来确定。这样时间复杂度是O(N^2)。总的时间复杂度是O(N^2)。一定要加上对重复元素的减枝处理。

runtime:68ms

class Solution {
public:
    vector
   
    > threeSum(vector
    
     & nums) { int length=nums.size(); vector
     
      > result; if(length<3) return result; sort(nums.begin(),nums.end()); auto iter1=nums.begin(); for(;iter1!=nums.end()-2;iter1++) { auto iter2=iter1+1; auto iter3=nums.end()-1; while(iter2
      
        tmp; tmp.push_back(*iter1); tmp.push_back(*iter2); tmp.push_back(*iter3); result.push_back(tmp); while(*iter2==*(iter2+1)&&(iter2+1)
       
      
     
    
   

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu2126 Buy the souvenirs 下一篇C++中vector使用

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: