leetcode-每日一道算法题

这篇文章讲解了如何使用Python实现一个解决方案来查找数组中满足a + b + c = 0的不重复三元组。通过三指针技巧,对数组进行排序并遍历,避免了重复元素。示例和代码展示了解决这个问题的具体步骤。
摘要由CSDN通过智能技术生成
  1. 三数之和
    给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]

示例 2:
输入:nums = []
输出:[]

示例 3:
输入:nums = [0]
输出:[]

代码:

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        /**
         * 三指针解法:
         * 1、数组排序
         * 2、中间指针作为校验
         * 3、两边指针的值相加,大于中间指针值的相反数则移动右指针,反之移动左指针
         * 4、移动左或者右指针时,如果与上一次值相同,则继续移动(去重)
         * 5、如果相等,则保存三个值,同时移动左右指针
         * 6、如果左右指针任意一个与中间指针重叠,则移动中间指针
         */
        List<List<Integer>> result = new ArrayList<>();
        Map<Integer, Integer> checkRepeat = new HashMap<>();
        //排序
        Arrays.sort(nums);
        for (int i = 1; i < nums.length - 1; i++) {
            int leftIndex = 0;
            int rightIndex = nums.length - 1;
            while (leftIndex != i && rightIndex != i){
                int first = nums[leftIndex];
                int second = nums[i];
                int third = nums[rightIndex];
                if (first + third == -second) {
                    leftIndex += 1;
                    rightIndex -= 1;
                    //判断重复,三数之中如果有两个数一样,则第三个数也一样
                    Integer checkValue = checkRepeat.get(first);
                    if (Integer.valueOf(second).equals(checkValue)){
                        continue;
                    }else {
                        List<Integer> list = new ArrayList<>();
                        list.add(first);
                        list.add(second);
                        list.add(third);
                        result.add(list);
                        checkRepeat.put(first, second);
                    }
                }else if (first + third > -second){
                    rightIndex -= 1;
                }else {
                    leftIndex += 1;
                }
            }
        }
        return result;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值