Two Sum类问题

这篇博客总结了Two Sum类问题的各种变形,包括两数之和II、3Sum Closest、4Sum等,探讨了使用排序、双指针、哈希表等方法解决这类问题的策略,并提供了相应的代码示例。还提到了在需要保持索引信息时如何设计数据结构,以及如何降低时间复杂度到O(n^2)的应用案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

##引言:
Two Sum类问题属于对撞型双指针问题,这类问题的思路不难,但是变形以及问法比较多,这里将部分题目做归纳总结。
在Two Sum问题中,需要用的预处理为排序。但有的时候需要返回索引的位置,就需要设计数据结构先保存索引信息,再进行排序。如果不想这样麻烦的话,可以借助哈希表这个常用的数据结构来代替双指针。
##题解:
1.两数之和 II Two Sum问题的基本变形,在一组整数中找出多少对整数,大于给定目标值。
基本思路:排序预处理 + 双指针
Code:

public class Solution {
    /**
     * @param nums: an array of integer
     * @param target: an integer
     * @return: an integer
     */
    public int twoSum2(int[] nums, int target) {
        // Write your code here
        if (nums == null || nums.length == 0) {
            return 0;
        }
        Arrays.sort(nums);
        int count = 0;
        int i = 0;
        int j = nums.length - 1;
        while (i < j) {
            if (nums[i] + nums[j] > target) {
                count += j - i;
                j--;
            } else {
                i++;
            }
        }
        return count;
    }
    
}

2.3Sum Closest
基本思路:2Sum Closet的变形。
这里有抽出函数的写法和不抽出函数的写法,
另外nums[A] + nums[B] + nums[C] = target + closet.
特别注意这里函数的写法和初始化推荐用函数写法

Code:

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        if (nums == null || nums.length < 3) {
            return -1;
        }
        Arrays.sort(nums);
        int closet = nums[0] + nums[1] + nums[2] - target;
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            int curr = twoSumCloset(nums, target - nums[i], left, right);
            closet = Math.abs(closet) > Math.abs(curr) ? curr : closet;
            
        }
        return target + closet;
    }
    private int twoSumCloset(int[] nums, int target, int left, int right) {
        int diff = nums[left] + nums[left + 1] - target;
        int start = left;
        int end = right;
        while (start < end) {
            int curr = nums[start] + nums[end] - target;
            if (Math.abs(curr) < Math.abs(diff)) {
                diff = curr;
            }
            if (nums[start] + nums[end] < target) {
                start++;
            } else {
                end--;
            }
        }
        return diff;
    }
}

3.4Sum
基本思路同3Sum…
分析:这里只是问法不同,返回所有的元组,另外还有个去重的技术,这里的写法就没有抽取函数了。
Code:

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> rst = new ArrayList<List<Integer>>();
        if (nums == null || nums.length == 0) {
            return rst;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 3; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j != i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int left = j + 1;
                int right = nums.length - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == target) {
                        ArrayList<Integer> tmp = new ArrayList<>();
                        tmp.add(nums[i]);
                        tmp.add(nums[j]);
                        tmp.add(nums[left]);
                        tmp.add(nums[right]);
                        rst.add(tmp);
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    } else if (sum < target) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }
        }
        return rst;
    }
}

4.Two Sum - Difference equals to target
在整数数组中,找到两数之差等于目标值的索引位置。
基本思路:由于要找索引,排序会破坏索引,所以我自己用的哈希表。
Code:

public class Solution {
    /*
     * @param nums an array of Integer
     * @param target an integer
     * @return [index1 + 1, index2 + 1] (index1 < index2)
     */
    public int[] twoSum7(int[] nums, int target) {
        // write your code here
        int[] res = new int[2];
        if (nums == null || nums.length == 0) {
            return res;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i] + target)) {
                res[0] = map.get(nums[i] + target) + 1;
                res[1] = i + 1;
                return res;
            }
            else if (map.containsKey(nums[i] - target)) {
                res[0] = map.get(nums[i] - target) + 1;
                res[1] = i + 1;
                return res;
            } else {
                map.put(nums[i], i);
            }
        }
        return res;
    }
}

然而这道问题可以用我引言中提到的方法,设计数据结构来存储索引信息,再来双指针(快慢型双指针)。
Code

5.三角形计数
基本思路:方法和问题1类似 (两边之和大于第三边)
Code:

public class Solution {
    /**
     * @param S: A list of integers
     * @return: An integer
     */
    public int triangleCount(int S[]) {
        // write your code here
        int left = 0, right = S.length - 1;
        int ans = 0;
        Arrays.sort(S);
        for(int i = 0; i < S.length; i++) {
            left = 0;
            right = i - 1;
            while(left < right) {
                if(S[left] + S[right] > S[i]) {
                    ans = ans + (right - left);
                    right --;
                } else {
                    left ++;
                }
            }
        }
        return ans;
    }
}

6.4Sum II
问题描述:给4个数组,问在这四个数组中各取一个数,构造成四元组。使其和等于目标值(0).
分析:2Sum的变形,借助哈希表,将时间复杂度降到O(n^2)。
Code:

public class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        Map<Integer, Integer> map = new HashMap<>();
        int count = 0;
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < B.length; j++) {
                map.put(A[i] + B[j], map.getOrDefault(A[i] + B[j], 0)+ 1);
            }
        }
        
        for (int i = 0; i < C.length; i++) {
            for (int j = 0; j < D.length; j++) {
                int target = -1 * (C[i] + D[j]);
                count += map.getOrDefault(target, 0);
            }
        }
        return count;
    }
}

7.盛最多水的容器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值