15. 3Sum

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.

 

 

  

 

posted @ 2018-09-30 22:00  Veritas_des_Liberty  阅读(118)  评论(0编辑  收藏  举报