【LeetCode】解题15:3Sum

本文详细解析了LeetCode上的经典题目3Sum问题,通过使用排序和双指针法,实现了时间复杂度为O(n^2)的高效解决方案。文章提供了Java实现代码,展示了如何避免重复解和优化搜索过程。

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

Problem 15: 3Sum [Medium]

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

来源:LeetCode

解题思路

  • 使用sort()对数组排序。
  • 遍历数组,并在当前数字nums[i]的后续数字nums[i+1]~nums[n-1]中,使用双指针法寻找和为-nums[i]的两个数。
  • 在遍历以及双指针移动过程中注意跳过重复的数字。

排序的时间复杂度O(n log n),遍历数组+双指针过程时间复杂度O(n2),总体时间复杂度O(n2)。

要点:排序双指针

Solution (Java)

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        int N = nums.length;
        if(N < 3) return result;
        
        int last = nums[0];
        int left, right, temp;
        for(int i = 0; i < N-2; i++){
            if(nums[i] > 0) break;
            if(nums[i] == last && i > 0) continue;
            last = nums[i];
            left = i+1;
            right = N-1;
            while(left < right){
                if(nums[i] + nums[left] + nums[right] == 0){
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    temp = nums[left];
                    while(++left < right && nums[left] == temp);
                }
                else if(nums[i] + nums[left] + nums[right] > 0){
                    temp = nums[right];
                    while(--right > left && nums[right] == temp);
                }
                else{
                    temp = nums[left];
                    while(++left < right && nums[left] == temp);
                }
            }
        }
        return result;
    }
}

修改过程

  • 考虑N<3的情况直接返回空。
  • 遍历数组的当前数字nums[i]若大于0,则后续的数字之和不会小于0(因为已从小到大排序),不可能出现三个数总和为0的情况,因此可直接跳出循环。
  • 在双指针移动过程中同样需要考虑跳过重复数字。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值