LeetCode 18.四数之和

问题描述

给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 nums\[a, numsb, numsc, numsd] (若两个四元组元素一一对应,则认为两个四元组重复):

复制代码
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target

你可以按 任意顺序 返回答案 。

示例 1:

输入:nums = 1,0,-1,0,-2,2, target = 0

输出:\[-2,-1,1,2,-2,0,0,2,-1,0,0,1]

示例 2:

输入:nums = 2,2,2,2,2, target = 8

输出:\[2,2,2,2]

Leetcode链接

解题思路

  1. 排序:首先对数组进行排序,这样可以方便地使用双指针来查找满足条件的四元组。

  2. 遍历:使用两层循环来固定前两个数,然后在剩下的数组中使用双指针来查找另外两个数。

  3. 去重:为了避免重复的四元组,需要在每次遍历时跳过相同的数。

code

java 复制代码
/**
 * @package: _03hash._18fourSum
 * @description:18.四数之和
 * @author: Yunyang
 * @date: 2024/10/23  14:10
 * @version:1.0
 **/
public class TestFourSum {
    public static void main(String[] args) {
        Solution solution = new Solution();

        int[] nums1 = {1, 0, -1, 0, -2, 2};
        int target1 = 0;
        System.out.println(solution.fourSum(nums1, target1)); // 输出: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

        int[] nums2 = {2, 2, 2, 2, 2};
        int target2 = 8;
        System.out.println(solution.fourSum(nums2, target2)); // 输出: [[2,2,2,2]]

        int[] nums3 = {1000000000,1000000000,1000000000,1000000000};
        int target3= -294967296;
        System.out.println(solution.fourSum(nums3, target3));
    }
}

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        // 初始化result数组
        List<List<Integer>> result = new ArrayList<>();

        if(nums == null || nums.length < 4){
            return result;
        }

        // 对数组 nums 进行排序
        Arrays.sort(nums);

        // 使用两层循环来固定前两个数 nums[i] 和 nums[j],
        // 然后在剩下的数组中使用双指针 left 和 right 来查找另外两个数
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            // 提前终止条件
            if (nums[i] > target && nums[i] >= 0){
               break;
            }

            // 跳过重复的元素
            if(i > 0 && nums[i] == nums[i - 1]){
                continue;
            }

            for (int j = i + 1; j < n - 1; j++) {
                // 提前终止条件
                if(nums[i] + nums[i] > target && nums[i] + nums[j] >= 0){
                    break;
                }

                // 跳过重复的元素
                if(j > i + 1 && nums[j] == nums[j - 1]){
                    continue;
                }

                int left = j + 1;
                int right = n - 1;

                while (left < right){
                    long sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == Integer.MIN_VALUE){
                        return result;
                    }

                    if(sum > target){
                        right--;
                    } else if(sum < target){
                        left++;
                    } else {
                        result.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));

                        // 跳过重复的元素
                        while (left < right && nums[left] == nums[left + 1]){
                            left++;
                        }

                        // 跳过重复的元素
                        while (left < right && nums[right] == nums[right - 1]){
                            right--;
                        }
                        left++;
                        right--;
                    }
                }
            }

        }
        return result;
    }
}

代码解释

  1. 整数溢出处理 :在计算 sum 时,使用 long 类型来避免整数溢出。
  2. 提前终止条件 :在 i 和 j 的循环中,添加提前终止条件,以减少不必要的计算。
  3. 去重:在每次遍历时跳过重复的元素,避免生成重复的四元组。
相关推荐
yi0116 小时前
LeetCode 219:存在重复元素 II——哈希表记录“最近一次出现的位置”
数据结构·人工智能·笔记·python·算法·leetcode·哈希表
好想像大佬一样能够ak所有10 小时前
Leetcode35.搜索插入位置
数据结构·算法·leetcode
aqiu11111110 小时前
【C++算法打怪专栏】LeetCode 165. 比较版本号(双指针与字符串流法)
c++·算法·leetcode
垆边人似月.14 小时前
华为OD算法题:查找众数及中位数
数据结构·算法·leetcode
CoderYanger14 小时前
一轮复习——F.动态规划模型总结(入门篇)
java·开发语言·数据结构·算法·leetcode·职场和发展·动态规划
浅念-15 小时前
动态规划专题:斐波那契数列模型 + 网格路径DP(LeetCode例题全解析)
笔记·算法·leetcode·面试·职场和发展·动态规划·推荐算法
夏幻灵15 小时前
每日一题:LeetCode 20:有效的括号——栈与哈希映射详解
算法·leetcode·哈希算法
Nil20816 小时前
leetcode 279完全平方数
算法·leetcode·职场和发展
longlongzihan16 小时前
前缀积与后缀积 —— LeetCode 238. 除了自身以外数组的乘积
开发语言·c++·leetcode
All for pursuit.16 小时前
【动态规划-1】121.买卖股票的最佳时机
数据结构·c++·算法·leetcode·动态规划