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;
        }
    }
  • 相关阅读:
    Java语言基础之流程控制语句
    localStorage的详细
    LeetCode374-猜数字大小(二分查找)
    LeetCode326-3的幂(很奇妙的水题)
    Angular学习-
    Angular学习-构建/部署
    JavaScript词法分析步骤
    IO模型
    解决You should consider upgrading via the 'python -m pip install --upgrade pip' command.
    协程
  • 原文地址:https://www.cnblogs.com/skillking/p/9410932.html
Copyright © 2011-2022 走看看