码迷,mamicode.com
首页 > 编程语言 > 详细

15. 3Sum C++

时间:2018-11-16 00:29:04      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:htm   rom   c++   forward   --   logs   process   push   return   

参考资料:

https://leetcode.com/problems/3sum/discuss/7402/Share-my-AC-C%2B%2B-solution-around-50ms-O(N*N)-with-explanation-and-comments

https://www.cnblogs.com/grandyang/p/4481576.html

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int> > res;

        std::sort(nums.begin(), nums.end());

        for (int i = 0; i < nums.size(); i++) {

            int target = -nums[i];
            int front = i + 1;
            int back = nums.size() - 1;

            while (front < back) {

                int sum = nums[front] + nums[back];

                // Finding answer which start from numsber nums[i]
                if (sum < target)
                    front++;

                else if (sum > target)
                    back--;

                else {
                    vector<int> triplet(3, 0);
                    triplet[0] = nums[i];
                    triplet[1] = nums[front];
                    triplet[2] = nums[back];
                    res.push_back(triplet);

                    // Processing duplicates of numsber 2
                    // Rolling the front pointer to the next different numsber forwards
                    while (front < back && nums[front] == triplet[1]) front++;

                    // Processing duplicates of numsber 3
                    // Rolling the back pointer to the next different numsber backwards
                    while (front < back && nums[back] == triplet[2]) back--;
                }

            }

            // Processing duplicates of numsber 1
            while (i + 1 < nums.size() && nums[i + 1] == nums[i]) 
                i++;

        }

        return res;
    }
};

 

15. 3Sum C++

标签:htm   rom   c++   forward   --   logs   process   push   return   

原文地址:https://www.cnblogs.com/tornado549/p/9966923.html

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