leetcode_4Sum、4Sum II

来源:互联网 发布:网络招生实战 丁丛 编辑:程序博客网 时间:2024/05/17 05:58

Given an array S of n integers, are there elements a, b, c, 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.

class Solution {    public List<List<Integer>> fourSum(int[] nums, int target) {        List<List<Integer>> res = new ArrayList<>();        if(nums==null || nums.length<4) return res;        Arrays.sort(nums);        for(int i=0; i<nums.length-3; i++){            if(i>0 && nums[i]==nums[i-1]) continue;            for(int j=i+1; j<nums.length-2; j++){                if(j>(i+1) && nums[j]==nums[j-1]) continue;                int left = j+1;                int right = nums.length-1;                while(left<right){                    if(nums[left]+nums[right]==target-nums[i]-nums[j]){                        res.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));                        while(left<right && nums[left]==nums[left+1]) left++;                        while(left<right && nums[right]==nums[right-1]) right--;                        left++;                        right--;                    }else if(nums[left]+nums[right]>target-nums[i]-nums[j]){                        right--;                    }else{                        left++;                    }                }            }        }        return res;    }}

4Sum就是在3Sum的外面在套一层循环就好了,需要注意的细节是循环的结束点以及跳过的值

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

class Solution {    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();        int count = 0;        for(int i=0; i<A.length; i++){            for(int j=0; j<B.length; j++){                int sumAB = A[i]+B[j];                if(map.containsKey(0-sumAB))                    map.put(0-sumAB,map.get(0-sumAB)+1);                else                    map.put(0-sumAB,1);            }        }        for(int k=0; k<C.length; k++){            for(int m=0; m<D.length; m++){                int sumCD = C[k]+D[m];                if(map.containsKey(sumCD)) count+=map.get(sumCD);            }        }        return count;    }}

4Sum II是利用hashmap,首先利用两个for循环将前两个数组相加的和(这里转换为0-相加的和作为hashmap的键值),如果另外两个数组相加的和在在这个map中,说明这四个数字相加的和为0。

原创粉丝点击