前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++版 - Leetcode 15. 3Sum 题解

C++版 - Leetcode 15. 3Sum 题解

作者头像
Enjoy233
发布2019-03-05 15:05:12
5860
发布2019-03-05 15:05:12
举报
文章被收录于专栏:大白技术控的技术自留地

C++版 - Leetcode 15. 3Sum 题解

在线提交网址: https://leetcode.com/problems/3sum/

  • Total Accepted: 158822
  • Total Submissions: 777492
  • Difficulty: Medium

Given an array S of n integers, are there elements a, b, c in S 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.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:

代码语言:javascript
复制
[
  [-1, 0, 1],
  [-1, -1, 2]
]

分析:

此题可以先对给定的数组进行排序,如果将a+b+c=0变形为a+b = -c(则 将问题转换成了2sum问题),然后使用双指针扫描来解决,另外注意去除重复…

AC代码:

代码语言:javascript
复制
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

class Solution {
    public:
        vector<vector<int> > threeSum(vector<int>& nums) {
            sort(nums.begin(), nums.end());   // 第一步是排序 
            vector<vector<int> > result;
            int len = nums.size();
            for(int i = 0; i< len; ++i) {
                int target = 0 - nums[i];  // a+b = -c
                int start = i+1, end = len-1;
                while(start < end) {
                    if(nums[start] + nums[end] == target) {
                        result.push_back({nums[i], nums[start], nums[end]});
                        start++;
                        end--;
                        while(start < end && nums[start] == nums[start-1]) start++;  // 过滤双指针扫描时的重复解: 遇到相等的数时, 跳过 
                        while(start < end && nums[end] == nums[end+1]) end--;        // 遇到相等的数时, 跳过 
                    } else if(nums[start] + nums[end] < target) {
                        start++;
                    } else {
                        end--;
                    }
                }
                if(i < len - 1) {
                    while(nums[i] == nums[i+1]) i++;   // 过滤外部扫描时的重复解: 遇到相等的数(target)时, 跳过 
                }
            }
            return result;
        }
};
// 以下为测试 
int main() {
    Solution sol;
    int arr[] = {-1, 0, 1, 2, -1, 1, 2, -4};
    vector<int> vec(arr, arr+6);
    vector<vector<int> > res = sol.threeSum(vec);
    for(auto it: res) {
        for(auto i: it) {
            cout<<i<<endl;
        }
        cout<<"----"<<endl;
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016年11月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C++版 - Leetcode 15. 3Sum 题解
    • 分析:
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档