18.四数之和

2020/10/1

比16多一层遍历,内部循环条件要求多些,16题只找出三数之和,此题找找到对应的不能有重复的数组

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> resultList = new ArrayList<>();
        Arrays.sort(nums);
        int length = nums.length;
        for(int i=0; i<length-3; i++){
            if(i>0 && nums[i]==nums[i-1]){
                continue;
            }
            if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
                break;
            }
            if (nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target) {
                continue;
            }
            for(int j=i+1; j<length-2; j++){
                if(j>i+1 && nums[j]==nums[j-1]){
                    continue;
                }
                    if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
                    break;
                }
                if (nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target) {
                    continue;
                }
                int L=j+1, R=length-1;
                while(L<R){
                    int sum = nums[i]+nums[j]+nums[L]+nums[R];
                    if(sum==target){
                        resultList.add(Arrays.asList(nums[i], nums[j], nums[L], nums[R]));
						//在sum==target的条件中两步:  
							1. 先循环判断是否要L++或R--;
							2. 再做出L++或R--进行下一个外层的循环
                        
                        while(L<R && nums[L]==nums[L+1]){  
                            L++;
                        }
                        L++;
                        while(L<R && nums[R]==nums[R-1]){
                            R--;
                        }
                        R--;
                        
                    }else if(sum>target){
                        
                        R--;
                    }else{
                        
                        L++;
                    }
                }


            }
        }
        return resultList;
    }
}
Last Updated: 4/4/2024