zoukankan      html  css  js  c++  java
  • [leetcode 15] 3Sum

    1 题目:

    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)

    2 思路:

    首先想到要排序。然后想到的是,既然要为0,那么肯定有负数(好吧,可以三个0),那么就要找到正数、负数的交接点,然后用两个指针,一个指向负数,一个指向正数,这样比较。

    结果,代码比较复杂,又是各种特殊问题,越界等,改了半天,还是不能通过。遂放弃,看看别人优秀的思路。

    https://leetcode.com/discuss/23638/concise-o-n-2-java-solution

    然后发现我就死心眼了,排序肯定是对的,那为什么非要从最小正数开始呢,可以从最大正数开始啊。。这样也不用管0的问题了。

    3 代码:

        public List<List<Integer>> threeSum(int[] nums) {
            Arrays.sort(nums);
            int len = nums.length;
            List<List<Integer>> answerList = new ArrayList<List<Integer>>();
            for(int i = 0 ; i < len - 2 ; i++){
                if(i == 0 || (i > 0 && nums[i]!=nums[i-1])){    
                    int hi = len -1;
                    int lo = i + 1;
                    int sum = 0-nums[i];
                    while(lo < hi){
                        if(nums[lo] + nums[hi] == sum){
                            answerList.add(Arrays.asList(nums[i],nums[lo],nums[hi]));
                            while(lo < hi && nums[lo] == nums[lo+1]) lo++;
                            while(lo < hi && nums[hi] == nums[hi-1]) hi--;
                            lo++;
                            hi--;
                        }else if (nums[lo] + nums[hi] < sum) lo++;
                        else hi--;
                    }
                }
            }
            return answerList;
        }
       



  • 相关阅读:
    css Tab选项卡1
    顺序栈的相关操作(初始化、入栈、出栈)
    用jdk在cmd下运行编译java程序
    UNIX标准及实现
    正则表达式
    gdb调试
    CSS 公共样式
    babel更新之后的 一些坑
    webpack4.x配置详情
    webpack4.x打包配置
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4576536.html
Copyright © 2011-2022 走看看