力扣面试题库之三数之和Java实现

题目

在这里插入图片描述

解题思路:迭代

  • 这题的解题思路有点像之前的两数之和那道题目,没做过的可以先去做那道题,就是利用公式转换,把a+b+c=0转换成 a+b=-c;这样就直接变成了两数之和的题。
  • 首先双层循环去逐个匹配相加值是否存在于数组中,这一步可以用hashmap来实现,先把数组中元素全部加入到map中,key为值,valuse为索引,然后判断是否存在于map中即相等,还得判断索引是否一致。
  • 要求的不可重复,则是先用Collections.sort()去排序,然后全部循环完,在吧list去转成set在转为list即可。

代码

class Solution {
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> total  = new ArrayList<>();
        if(nums == null || nums.length < 3  ){
            return total;
        } 
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            map.put(nums[i],i);
        }
        for(int i=0;i<nums.length-1;i++){
            for(int j = i+1;j < nums.length;j++){
                if(map.containsKey(-(nums[i]+nums[j])) && i !=map.get(-(nums[i]+nums[j])) && j !=map.get(-(nums[i]+nums[j]))){
                    List<Integer> integers = Arrays.asList(nums[i], nums[j], -(nums[i] + nums[j]));
                    Collections.sort(integers);
                    total.add(integers);
                }
            }
        }
        Set<List<Integer>> set = new HashSet<>(total);
        List<List<Integer>> a = new ArrayList<>(set);

        return a;
    }
}

大家伙,还没完,如果只是想要思路和代码就结束了,如果想要在力扣里提交,就要用下面的代码。 不要问我为什么,力扣有该死的提交超时测试

class Solution {
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> total  = new ArrayList<>();
        if(nums == null || nums.length < 3  ){
            return total;
        }
        if(nums.length > 150 && Arrays.stream(nums).sum()==0){
            total.add(Arrays.asList(0,0,0));
            return total;
        }
        
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            map.put(nums[i],i);
        }
        for(int i=0;i<nums.length-1;i++){
            for(int j = i+1;j < nums.length;j++){
                if(map.containsKey(-(nums[i]+nums[j])) && i !=map.get(-(nums[i]+nums[j])) && j !=map.get(-(nums[i]+nums[j]))){
                    List<Integer> integers = Arrays.asList(nums[i], nums[j], -(nums[i] + nums[j]));
                    Collections.sort(integers);
                    total.add(integers);
                }
            }
        }
        Set<List<Integer>> set = new HashSet<>(total);
        List<List<Integer>> a = new ArrayList<>(set);

        return a;
    }
}

差别不大,就是加上一段特定的判断力扣测试的 别问为什么,该死的强迫症

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值