LeetCode 4Sum

来源:互联网 发布:网络存储器怎么用 编辑:程序博客网 时间:2024/05/18 15:04

原题链接在这里:https://leetcode.com/problems/4sum/

这道题其实是3Sum的扩展,使用的方法基本相同,只是多加了一层loop.

但要注意一点:For inner j loop, if statement, 判断overflow 时要写成 j>i+1, 而不是j>0, 与 j 的 初始条件有关。若是写成j>0的话,含有四个相同数的输入就会被跳过。e.g. 0,0,0,0 target = 0.

 

AC Java:

public class Solution {    public List<List<Integer>> fourSum(int[] nums, int target) {        List<List<Integer>> res = new ArrayList<List<Integer>>();                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]){ //error 0,0,0,0                    continue;                }                int l = j+1;                int r = nums.length-1 ;                while(l<r){                    int sumFour = nums[i] + nums[j] + nums[l] + nums[r];                    if(sumFour<target){                        l++;                    }else if(sumFour>target){                        r--;                    }else{                        List<Integer> subList = new ArrayList<Integer>();                        subList.add(nums[i]);                        subList.add(nums[j]);                        subList.add(nums[l]);                        subList.add(nums[r]);                        res.add(subList);                                                l++;                        r--;                        while(l<r&&nums[l] == nums[l-1]){                            l++;                        }                        while(l<r&&nums[r] == nums[r+1]){                            r--;                        }                    }                }            }        }                return res;    }}



0 0