zoukankan      html  css  js  c++  java
  • 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.

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    第十次作业
    第九次作业
    第八次作业总结
    第八次作业
    C语言总结(6)
    作业十二总结
    作业十一总结
    实验十总结
    实验九总结
    第一次附加作业
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9733476.html
Copyright © 2011-2022 走看看