• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
THE WAY I AM
博客园    首页    新随笔    联系   管理    订阅  订阅
15. 3Sum C++

参考资料:

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;
    }
};

 

posted on 2018-11-15 23:46  549  阅读(123)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3