编程题:3sum,乱序数组

本文深入探讨了经典的三数之和算法,旨在寻找数组中三个数相加等于零的所有唯一组合,避免重复的解决方案。文章详细介绍了算法的实现过程,包括数组排序、跳过重复元素等关键步骤。

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

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]
]

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new  ArrayList<>();
        //先把数组排序
        Arrays.sort(nums);
        for(int i=0;i<nums.length-2;i++){
            //跳过重复的,因为结果一定会一样
            if(i!=0 && nums[i]==nums[i-1]){
                continue;
            }
            int key = 0-nums[i];
            int j=i+1;
            int e=nums.length-1;
            while(j<e){
                if(nums[j]+nums[e]==key){  
                    //当前有一个结果,加到最终结果里
                    res.add(Arrays.asList(nums[i],nums[j],nums[e]));
                    j++;
                    while(nums[j]==nums[j-1] && j<e){
                        j++;
                    } 
                }
                else if(nums[j]+nums[e]<key){
                    j++;
                }else {
                    e--;
                }
            }
        }
        return res;
    }
}

KEYPOINT

未排序,所以先排序Arrays.sort(nums);
注意要

 if(i!=0 && nums[i]==nums[i-1]){
                continue;
            }

while(nums[j]==nums[j-1] && j<e){
                        j++;
                    } 

跳过重复的,结果里不能重复

这样加方便点
但其实Arrays.asList适合对象,不适合基本类型
res.add(Arrays.asList(nums[i],nums[j],nums[e]));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值