• 【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;
        }
        
    }
  • 相关阅读:
    后端Golang+前端React架构开发案例
    Vim技巧大全
    Draggable Modal dialog in Bootstrap
    Github.com的镜像站
    kettle之excel上传数据库
    自定义函数之分割函数
    jmeter 压测 ActiveMq 消息队列
    SQL---查找+删除重复记录
    异常值检测(Outlier Detection)
    使用u盘在pc上安装centos7(安装停留在dracut:/#的处理)
  • 原文地址:https://www.cnblogs.com/sMKing/p/6573796.html
Copyright © 2020-2023  润新知