zoukankan      html  css  js  c++  java
  • 18. 4Sum

    一、题目

      1、审题

        

      2、分析:

        求所给数组中选取4个数字之和等于 target 的所有组合。

    二、解答

      1、分析:

        a、数组进行排序,依次遍历数组下标为 i 的元素 ;

        b、遍历元素时,target - nums[i]  即为 剩余的数组中的元素求三数之和。

      

    class Solution {
        public List<List<Integer>> fourSum(int[] nums, int target) {
    
            List<List<Integer>> resultList = new ArrayList<List<Integer>>();
            int len = nums.length;
            if(len < 4)
                return resultList;
    
            Arrays.sort(nums);
            for (int i = 0; i < len - 3; i++) {
                int threeSum = target - nums[i];
    
                if(i == 0 || nums[i] != nums[i-1])  // 
                    
                for (int j = i+1; j < len - 2; j++) {
                    int low = j + 1, high = len - 1;
    
    
                    while (low < high) {
                        int sum = nums[j] + nums[low] + nums[high];
                        if (sum == threeSum) {
                            resultList.add(Arrays.asList(nums[i], nums[j], 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 (sum > threeSum)
                            high--;
                        else
                            low++;
                    }
                }
            }
            // 去重
            List<List<Integer>> list = new ArrayList<List<Integer>>(new HashSet(resultList));
            return list;
        }
    }
  • 相关阅读:
    基数排序学习
    桶排序学习
    计数排序-不基于比较O(n)
    基尼系数
    拉普拉斯进行特征选择
    int ,long long等范围
    Codeforces780C
    51 Nod 1119
    字典树入门
    POJ 2531 暴力深搜
  • 原文地址:https://www.cnblogs.com/skillking/p/9410932.html
Copyright © 2011-2022 走看看