题目

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:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

解答

看这个题目,首先想到的是暴力枚举,不过做完之后看了网上的一些解答,好像暴力枚举确实是可以的。

但是作为一个可爱的娃的爸爸,我肯定是先想到排序,这样就算是暴力枚举,应该也会方便一丢丢?
不管怎么样先做个排序,排序完之后就要冷静的想一想这个问题的本质,毕竟除了3sum,这个题还可以出成4sum,5sum什么的。

我们知道,如果把这个题目改成求2sum,那么就很简单了,从头开始遍历,先确定第一个数,确定了第一个数后从尾开始遍历,不断尝试第二个数。
那么我们就可以递归的来思考这个问题,我们可以把这个问题看成,找到所有由一个数和一个2sum构成的组合,这样就很简单了。
于是我们同样从头开始遍历,先确定第一个数a,然后问题就变成,在a后面的数组中,求2sum,且2sum的和为-a。

下面是AC的代码,可能我细节方面做的还不够好,我的这个解法只能击败80%的答题者:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int i, j, k, m;
        int length = nums.size();
        int temp;
        vector<vector<int>> ans;

        if(length == 0){
            return ans;
        }
        sort(nums.begin(), nums.end());
        if(nums.front() > 0 || nums.back() < 0){
            return ans;
        }
        for(i = 0; i < length - 2; i++){
            if(i > 0 && nums[i - 1] == nums[i]){
                continue;
            }
            for(j = i + 1, k = length - 1; j < k; ){
                if(nums[i] + nums[j] + nums[k] == 0){
                    vector<int> temp;
                    temp.push_back(nums[i]);
                    temp.push_back(nums[j]);
                    temp.push_back(nums[k]);
                    ans.push_back(temp);
                    j++;
                    while(j < k && nums[j] == nums[j - 1]){
                        j++;
                    }
                    k--;
                    while(j < k && nums[k] == nums[k + 1]){
                        k--;
                    }
                }
                else if(nums[i] + nums[j] + nums[k] < 0){
                    j++;
                }
                else{
                    k--;
                }
            }
        }
        return ans;
    }
};

101

LeetCode OJ 15. 3Sum的更多相关文章

  1. LeetCode:15. 3Sum(Medium)

    1. 原题链接 https://leetcode.com/problems/3sum/description/ 2. 题目要求 数组S = nums[n]包含n个整数,请问S中是否存在a,b,c三个整 ...

  2. 【LeetCode】15. 3Sum 三数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:3sum, 三数之和,题解,leetcode, 力扣,P ...

  3. 【一天一道LeetCode】#15 3Sum

    一天一道LeetCode系列 (一)题目 Given an array S of n integers, are there elements a, b, c in S such that a + b ...

  4. 《LeetBook》leetcode题解(15):3Sum[M]

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  5. LeetCode OJ:3Sum Closest(最接近的三数之和)

    Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...

  6. Leetcode Array 15 3sum

      思考的方向不对,即使用了多于别人几倍的时间,也不一定能够达到终点. 我的错误的想法(可以跳过):在leetcode上面做的第四道题,走路一个很大的弯路,收到之前做过的 Container With ...

  7. 【LeetCode】15. 3Sum 三个数和为0

    题目: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find al ...

  8. 【leetcode】15. 3Sum

    题目描述: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find ...

  9. [LeetCode]题15:3Sum

    第一次解: res = [] nums.sort() if len(nums)<3:return [] for i in range(len(nums)-2): left = i+1 right ...

随机推荐

  1. Xmanager远程连接CentOS7

    上周例会,又被说了一通,Xmanager远程连接的文档没写?服务没搭建?心想这都有VNC了,为毛一定要弄这个啊?!!但是,我还是在今天给弄了,╮(╯▽╰)╭没人权.搭建完尝试用了下,感觉吧,也不咋地啊 ...

  2. MySQL数据库order by 奇慢无比

    今天遇到个奇葩的问题, sql 数据量很大 有where 和order by,不加order by 速度很快,加了就很慢 一.首先我们对这条sql执行查询计划: explain select t.or ...

  3. go语言功能代码

    一.数据类型转换 package main import ( "fmt" "strconv" ) func main() { //int到string str ...

  4. tf.nn.nce_loss

    def nce_loss(weights,biases,inputs,labels,num_sampled,num_classes,num_true=1,sampled_values=None,rem ...

  5. 微信小程序 - 布局练习

    1.小程序的布局就多了一个flex布局,其他和之前html没太大区别 ,先看代码: (1)wxml <view class='container'> <view class='sel ...

  6. jquery遍历指定元素下的img图片改变其路径

    $(".jieshao img").each(function (i) { $(this).attr("src", "manager/" + ...

  7. 用Python进行人脸识别

    本文的模型使用了C++工具箱 dlib 基于深度学习的最新人脸识别方法,基于户外脸部数据测试库Labeled Faces in the Wild 的基准水平来说,达到了99.38%的准确率. dlib ...

  8. python 中logging模块

    logging的作用:python中,logging模块主要是处理日志的.所谓日志,可理解为在软件运行过程中,所记录的的一些运行情况信息,软件开发人员可以根据自己的需求添加日志,日志可以帮助软件开发人 ...

  9. redis如何随系统启动

    Redis可以通过命令redis-server启动,但这种启动方式适用于开发环境,对于生产环境来说,配置好redis的配置文件,并使redis随linux启动则更加方便些,下面则记录下redis如何随 ...

  10. VMware虚拟机上配置nginx后,本机无法访问问题

    nginx装在CentOS上,用本机访问虚拟机的时候却出现了不能访问的问题,查了资料以后,原来是防火墙的问题.具体情况如下:防火墙可以ping通虚拟机,虚拟机也可以ping通防火墙.接着检查了服务器端 ...