zoukankan      html  css  js  c++  java
  • 【LeetCode】15. 3Sum

    3Sum

    Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

    Note:

    • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
    • 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)

    先升序排序,然后用第一重for循环确定第一个数字。

    然后在第二重循环里,第二、第三个数字分别从两端往中间扫。

    如果三个数的sum等于0,得到一组解。

    如果三个数的sum小于0,说明需要增大,所以第二个数往右移。

    如果三个数的sum大于0,说明需要减小,所以第三个数往左移。

    时间复杂度:O(n2)

    注意:

    1、排序之后天然满足non-descending order的要求

    2、为了避免重复,在没有空间要求情况下可以用map,但是也可以跳过重复元素来做。

    class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            vector<vector<int> > ret;
            int size = num.size();
            sort(num.begin(), num.end());
            for(int i = 0; i < size; i ++)
            {
                //skip same i
                while(i > 0 && i < size && num[i] == num[i-1])
                    i ++;
                int j = i + 1;
                int k = size - 1;
                while(j < k)
                {
                    int sum = num[i] + num[j] + num[k];
                    if(sum == 0)
                    {
                        vector<int> cur(3);
                        cur[0] = num[i];
                        cur[1] = num[j];
                        cur[2] = num[k];
                        ret.push_back(cur);
                        j ++;
                        k --;
                        //skip same j
                        while(j < k && num[j] == num[j-1])
                            j ++;
                        //skip same k
                        while(k > j && num[k] == num[k+1])
                            k --;
                    }
                    else if(sum < 0)
                    {
                        j ++;
                        //skip same j
                        while(j < k && num[j] == num[j-1])
                            j ++;
                    }
                    else
                    {
                        k --;
                        //skip same k
                        while(k > j && num[k] == num[k+1])
                            k --;
                    }
                }
            }
            return ret;
        }
    };

  • 相关阅读:
    windows计数器和瓶颈
    SQL Server 2005的Resource数据库
    Android学习笔记 json数据的解析
    android的消息处理机制(图+源码分析)——Looper,Handler,Message
    JS刷新验证码
    Java取得Unix的timestamp
    (转载)DBMS_SQL package 学习
    关于Java中Http下载的一些整理
    (转载)sqlserver内存释放
    关于EL表达式
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3832180.html
Copyright © 2011-2022 走看看