zoukankan      html  css  js  c++  java
  • [leetcode] 18. 四数之和

    18. 四数之和

    和之前的三数之和思路完全一样,只不过需要先枚举两个数,然后采用贪心的双指针法。

    class Solution {
        public List<List<Integer>> fourSum(int[] nums, int target) {
            Arrays.sort(nums);
            int p, q;
            int len = nums.length;
            if (len < 4) {
                return new ArrayList<>();
            }
            int less = nums[0] + nums[1] + nums[2] + nums[3];
            if (less > target) {
                return new ArrayList<>();
            }
            int more = nums[len - 1] + nums[len - 2] + nums[len - 3] + nums[len - 4];
            if (more < target) {
                return new ArrayList<>();
            }
    
            List<List<Integer>> ans = new ArrayList<>();
    
            for (p = 0; p <= len - 4; p++) {
                // 对于重复出现的数字,枚举一次就够了
                if (p > 0 && nums[p] == nums[p - 1]) continue;
                for (q = p + 1; q <= len - 3; q++) {
                    // 对于重复出现的数字,枚举一次就够了
                    if (q > p + 1 && nums[q] == nums[q - 1]) continue;
                    int i = q + 1, j = len - 1;
                    while (i < j) {
                        int tmp = nums[p] + nums[q] + nums[i] + nums[j];
                        if (tmp == target) {
                            ans.add(Arrays.asList(nums[p], nums[q], nums[i], nums[j]));
                            i++;
                            j--;
                            // 对于重复出现的数字,枚举一次就够了;这两个while保证不会有重复的结果
                            while (i < j && nums[i] == nums[i - 1]) i++;
                            while (i < j && nums[j] == nums[j + 1]) j--;
                        } else if (tmp < target) {
                            i++;
                        } else {
                            j--;
                        }
                    }
                }
            }
    
            //return ans.stream().distinct().collect(Collectors.toList());
            return ans;
        }
    }
    
  • 相关阅读:
    安卓AlertDialog的使用
    蚂蚁的腿
    年龄排序
    Digital Roots
    小明的存钱计划
    不高兴的小明
    管闲事的小明
    小明的调查作业
    爱摘苹果的小明
    小明的难题
  • 原文地址:https://www.cnblogs.com/acbingo/p/9250692.html
Copyright © 2011-2022 走看看