复杂度是o3 先排序,关键还是要处理连续重复数据,i和j都要取一串连续数字中最左面的那一个

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        if (nums.length < 4) {
            return results;
        }
        
        List<Integer> numList = new ArrayList<Integer>();
        for (int num: nums) {
            numList.add(num);
        }
        Collections.sort(numList);
        for (int i = 0; i < numList.size(); i++) {
            nums[i] = numList.get(i);
        }
        
        for (int i = 0; i < nums.length - 3; i++) {
            while(i<nums.length-3 && i!=0&& (nums[i-1]==nums[i])){
                i++;
            }
            for (int j = i+1;j<nums.length-2;j++) {
                while(j<nums.length-2&&j!=i+1&& (nums[j-1]==nums[j])) {
                    j++;
                }
                int p = j+1;
                int q = nums.length-1;
                while(p<q){
                    if(nums[p]+nums[q]<target-nums[i]-nums[j]){
                        p++;
                    } else if(nums[p]+nums[q]>target-nums[i]-nums[j]) {
                        q--;
                    } else {
                        List<Integer> result = Arrays.asList(new Integer[]{nums[i],nums[j],nums[p],nums[q]});
                        results.add(result);
                        int nums_p = nums[p];
                        int nums_q = nums[q];
                        p++;
                        q--;
                        while(p<q && nums_p == nums[p]) {
                            p++;
                        }

                        while(p<q && nums_q == nums[q]) {
                            q--;
                        }
                    }
                }
            }
        }
        return results;
    }
}

chenatu
106 声望12 粉丝