zoukankan      html  css  js  c++  java
  • LeetCode--015--三元之和(java)

    给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

    注意:答案中不可以包含重复的三元组。

    例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
    
    满足要求的三元组集合为:
    [
      [-1, 0, 1],
      [-1, -1, 2]
    ]

    i做主线的遍历,从头至尾寻找满足条件的其他两个数字。
    class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            Arrays.sort(nums);
            for(int i = 0;i < nums.length-2;i++){
                if(i > 0 && nums[i] == nums[i - 1])continue;//一定要加这一句,否则会重复,所给例子会输出两个[-1,1,0]
                int low = i + 1,high = nums.length-1,sum = 0 - nums[i];
                while(low < high){
                    if(nums[low] + nums[high] == sum){
                    res.add(Arrays.asList(nums[i],nums[low],nums[high]));
                    while(low < high && nums[low] == nums[low + 1]) low++;
                    while(low < high && nums[high] == nums[high - 1]) high--;
                    low ++;
                    high--;
                    }else if(nums[low] + nums[high] < sum){
                        low ++;
                    }else high--;
                }
                
            }
            return res;
        }
    }

     2019-04-14 09:49:33

  • 相关阅读:
    springcloud--zuul(过滤器)
    springcloud--ruul(路由网关)
    spingcloud--hystrix(断路器)
    springcloud--Feign(WebService客户端)
    springcloud--ribbo(负载均衡)
    IO流常用模式
    ArrayList与LindedList区别
    抽象类与接口的区别
    SpringMVC核心
    MVC设计模式
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/10704029.html
Copyright © 2011-2022 走看看