4Sum based on 3Sum


  • 0
    public List<List<Integer>> fourSum(int[] nums, int target) {
            List<List<Integer>> res = new ArrayList<>();
            if(nums.length < 4){
                return res;
            }
            Arrays.sort(nums);
            for(int i = 0 ; i < nums.length; i++){
                if(i > 0 && nums[i] == nums[i-1]){
                    continue;
                }
                int sum = target - nums[i];
                List<List<Integer>> temp = threeSum(sum, nums, i+1, nums.length-1);
                
                for(List<Integer> list : temp){
                    list.add(0, nums[i]);
                    res.add(list);
                }
            }
            return res;
        }
        
        public List<List<Integer>> threeSum(int sum, int[] nums, int start, int end){
            List<List<Integer>> res = new ArrayList<>();
            for(int i = start; i < end; i++){
                if(i > start && nums[i] == nums[i-1]){
                    continue;
                }
                int target = sum - nums[i];
                int left = i+1;
                int right = nums.length-1;
                while(left < right){
                    if(nums[left] + nums[right] == target){
                        List<Integer> temp = new ArrayList<>(Arrays.asList(nums[i], nums[left], nums[right]));
                        res.add(temp);
                        left++;
                        right--;
                        while(left < right && nums[left] == nums[left-1]){
                            left++;
                        }
                        while(left < right && nums[right] == nums[right+1]){
                            right--;
                        }
                    }else if(nums[left] + nums[right] < target){
                        left++;
                    }else{
                        right--;
                    }
                }
            }
            return res;
        }
        
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.