码迷,mamicode.com
首页 > 其他好文 > 详细

15. 3Sum

时间:2018-09-30 22:43:55      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:ret   for   pre   ==   nta   share   ica   note   ons   

Given an array nums of n integers, are there elements abc in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

AC code:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int len = nums.size();
        vector<vector<int> > v;
        sort(nums.begin(), nums.end());
        int front, tear, target, sum;
        for (int i = 0; i < len; ++i) {
            target = -nums[i];
            front = i + 1;
            tear = len-1;
            while (front < tear) {
                sum = nums[front] + nums[tear];
                if (sum < target) {
                    front++;
                } else if (sum > target) {
                    tear--;
                } else {
                    vector<int> sub_ans(3, 0);
                    sub_ans[0] = nums[i];
                    sub_ans[1] = nums[front];
                    sub_ans[2] = nums[tear];
                    v.push_back(sub_ans);
                    while (front < tear && nums[front] == sub_ans[1])
                        front++;
                    while (front < tear && nums[tear] == sub_ans[2])
                        tear--;
                }
            }
            while ((i+1) < len && nums[i] == nums[i+1]) {
                i++;
            }
        }
        return v;
    }
};
Runtime: 120 ms, faster than 40.59% of C++ online submissions for 3Sum.

 

 

  

 

15. 3Sum

标签:ret   for   pre   ==   nta   share   ica   note   ons   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/9733476.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!