力扣18. 四数之和

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(nums == null || nums.length <= 3) return res;
        Arrays.sort(nums);
        int index = 0;
        while(index < nums.length - 3 ){//外层嵌套一个循环
            int i = index + 1;//第二个数的起始位置为第一个数的后一位,后面就相当于threeSum
            while(i < nums.length-2){
                int base = nums[i];
                int left = i+1;
                int right = nums.length-1;
                while(left < right){
                    int sum = nums[index] + base + nums[right] + nums[left];
                    if(sum == target){
                        LinkedList<Integer> list = new LinkedList<Integer>();
                        list.add(nums[index]);
                        list.add(base);
                        list.add(nums[left]);
                        list.add(nums[right]);
                        res.add(list);
                        left = moveRight(nums,left+1);
                        right = moveLeft(nums,right-1);                   
                    }
                    else if(sum > target){
                        right = moveLeft(nums,right-1);   
                    }
                    else{
                        left = moveRight(nums,left+1);
                    }
                }
                i = moveRight(nums, i+1);
            }
            index = moveRight(nums, index+1);

        }
        return res;
    }
    
    public int moveLeft(int[] nums, int right){
        while((nums[right] == nums[right+1] && right > 0) || right == nums.length-1){
            right--;
        }
        return right;
    }

    public int moveRight(int[] nums, int left){
        while((nums[left] == nums[left-1] && left < nums.length-1) || left == 0){
            left++;
        }
        return left;
    }
}

归纳:
注意四个指针的初始位置和移动方向,第一个、第二个和第三个指针的初始位置是挨着的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值