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);
        }
  • 相关阅读:
    sass的安装
    git上传项目到github教程
    v-if 和v-show的区别
    es5实现数组去重
    原生js实现选中所有的checkbox
    拨打手机号
    H5页面打开小程序
    h5 网页 直接唤起淘宝app,并跳转到对应商品页面
    webstorm配置git
    elementUi 日历添加可选区间(只能选择一个月的时间段)
  • 原文地址:https://www.cnblogs.com/zyf-yxm/p/10950785.html
Copyright © 2011-2022 走看看