zoukankan      html  css  js  c++  java
  • 计算a+b+c=0

    public static List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> results = new ArrayList<>();
            
            if (nums == null || nums.length < 3) {
                return results;
            }
            
            Arrays.sort(nums);
    
            for (int i = 0; i < nums.length - 2; i++) {
                // skip duplicate triples with the same first numebr
                if (i > 0 && nums[i] == nums[i - 1]) {
                    continue;
                }
    
                int left = i , right = nums.length - 1;
                int target = -nums[i];
                
                twoSum(nums, left, right, target, results);
            }
            
            return results;
        }
        
        public static void twoSum(int[] nums,
                           int left,
                           int right,
                           int target,
                           List<List<Integer>> results) {
            while (left < right) {
                if (nums[left] + nums[right] == target) {
                    ArrayList<Integer> triple = new ArrayList<>();
                    triple.add(-target);
                    triple.add(nums[left]);
                    triple.add(nums[right]);
                    results.add(triple);
                    
                    left++;
                    right--;
                    // skip duplicate pairs with the same left
                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    // skip duplicate pairs with the same right
                    while (left < right && nums[right] == nums[right + 1]) {
                        right--;
                    }
                } else if (nums[left] + nums[right] < target) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        
        @Test
        public void testsum(){
            int [] nums={1,1,0,4,2,3,-5,-2};
            List<List<Integer>> threeSum = threeSum(nums);
            System.out.println(threeSum);
        }
  • 相关阅读:
    常用sql经典语句
    sql创建 自定义函数返回当前日期所在月的第一天最后一天
    洗洗睡了吧啊,何必在意……费口舌不热么
    asp.net Treeview控件
    MSSQL 触发器
    Mssql 通配符
    C#实现所有经典排序算法
    asp.net Treeview
    Asp.net+json 操作类
    Queue 和Stack 的区别
  • 原文地址:https://www.cnblogs.com/zyf-yxm/p/10950785.html
Copyright © 2011-2022 走看看