LC18.四数之和(双指针)

问题

问题

解题

  • 题目解法同三数之和,双指针,枚举前面两个数,确定前两个数的和sum之后,在后面使用双指针找 -sum即可。
  • 步骤:
    • 先从小到大排序
    • 再使用指针a确定第一个数,注意要跳过后面出现的重复的数
    • 再枚举a后面的第二个数b,注意也要跳过后面出现的重复的数
    • 双指针枚举c和d,两边向中间枚举,如果大于target则d–,否则c++,注意也要跳过重复的数。
  • 需要注意的是a和b在跳过重复数的时候,不能采用nums[i + 1] == nums[i]的判断方式,因为这样会跳过第一个出现的值,而我们应该跳过的是后面出现的重复的值。
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList();
        Arrays.sort(nums);
        int a, b, c, d;
        int n = nums.length;
        if(n < 4) return res;

        for(a = 0; a <= n - 4; a ++){
            if(a > 0 && nums[a - 1] == nums[a]){
                continue;
            }
            for(b = a + 1; b <= n - 3; b ++){
                if(b > a + 1 && nums[b - 1] == nums[b]){
                    continue;
                }
                c = b + 1;
                d = n - 1;
                while(c < d){
                    if(nums[a] + nums[b] + nums[c] + nums[d] < target){
                        c ++;
                    }else if(nums[a] + nums[b] + nums[c] + nums[d] > target){
                        d --;
                    }else{
                        res.add(Arrays.asList(nums[a],nums[b],nums[c],nums[d]));
                        while(c < d && nums[c + 1] == nums[c]){
                            c ++;
                        }
                        while(c < d && nums[d - 1] == nums[d]){
                            d --;
                        }
                        c ++;
                        d --;
                    }
                }
            }
        }
        return res;
        
    }
}   

猜你喜欢

转载自blog.csdn.net/qq_41423750/article/details/107026245
今日推荐