• 【LeetCode】4Sum


    Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

    Note: The solution set must not contain duplicate quadruplets.

    For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.A solution set is:[[-1, 0, 0, 1],[-2, -1, 1, 2],[-2, 0, 0, 2]]

    这种是一类问题,即KSum问题

    4Sum可以类比于3Sum,做法与3Sum一样。相当于在3Sum的基础上。再嵌套一层for循环。

    public class test2 {
        public static void main(String[] args) {
            int[] array = {1,0,-1,0,2,-2};
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            res = fourSum(array,0);
            for (int i = 0; i < res.size(); i++) {
                System.out.print("[");
                for(int j =0;j<res.get(i).size();j++){
                    System.out.print(res.get(i).get(j)+" ");
                }
                System.out.println("]");
            }
        }
    
        public static List<List<Integer>> fourSum(int[] nums,int target){
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            int len = nums.length;
            if(nums==null || len<4){
                return null;
            }
            Arrays.sort(nums);
            for(int i = 0;i<len-3;i++){
                for(int j=i+1;j<len-2;j++){
                    int start = j+1;
                    int end = len-1;
                    while(start<end){
                        int temp = nums[i]+nums[j]+nums[start]+nums[end];
                        if(temp==target){
                            res.add(Arrays.asList(nums[i],nums[j],nums[start],nums[end]));
                            start++;
                            end--;
                        }else if(temp<target){
                            start++;
                        }else{
                            end--;
                        }
                    }
                }
            }
            return res;
        }
        
    }
  • 相关阅读:
    html position定位
    设置input标签的placeholder的样式
    由于html元素加载导致的问题
    js setInterval参数设置
    .mht文件转换为html
    js异步导致的错误
    Premiere入门1 —— PR的下载、安装与优化
    Photoshop入门1 —— PS的下载、安装与优化
    Python正课25 —— 文件处理
    Python问题集
  • 原文地址:https://www.cnblogs.com/sMKing/p/6573796.html
Copyright © 2020-2023  润新知