【LeetCode】15. 三数之和(双指针)

题目

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。


注意

  • 列表添加元素:

        List<List<Integer>> list = new ArrayList<List<Integer>>();

        List<Integer> lists = new ArrayList<Integer>();

        lists.add(nums[left]);

        lists.add(nums[i]);

        lists.add(nums[right]);

        list.add(lists);

  • 对数组进行排序:

        Arrays.sort(nums);

  • 去除重复解:

        HashSet h = new HashSet(list);

        list.clear();

        list.addAll(h);

  • 双指针(左指针 left = i + 1,右指针 right = l - 1):

        if (nums[i] + nums[left] + nums[right] == 0)     

                left++;        right--;

        if (nums[i] + nums[left] + nums[right] < 0) 

                left++;

        if (nums[i] + nums[left] + nums[right] > 0) 

                right--;

代码

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        int l = nums.length;
        for (int i = 0; i < l - 1; i++) {
            int left = i + 1, right = l - 1;
            while (left < right) {
                if (nums[i] + nums[left] + nums[right] == 0) {
                    List<Integer> lists = new ArrayList<Integer>();
                    lists.add(nums[left]);
                    lists.add(nums[i]);
                    lists.add(nums[right]);
                    list.add(lists);
                    left++;
                    right--;
                } else if (nums[i] + nums[left] + nums[right] < 0) {
                    left++;
                } else if (nums[i] + nums[left] + nums[right] > 0) {
                    right--;
                }
            }
        }
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }
}
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值