首页 > 其他分享 >力扣写题记录15-三数之和

力扣写题记录15-三数之和

时间:2023-02-07 21:34:55浏览次数:44  
标签:right Arrays nums ++ 三数 力扣 写题 int left

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

java知识点:

1.数组可以用Arrays.sort()排序

2.Arrays.asList()将三个元素转为数组

解题思路:

首先将数组从小到大排序,然后使用三个指针,i,left,right,i固定,和大于0right--,小于0left++

注意事项:

1.nums[i]大于0直接结束

2.i的去重是在计算和之前与i-1比较,不是i+1

3.left和right的去重在找到三元组之后,未找到不需要去重,也不需要再移动

代码如下:

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; i ++) {
            if(nums[i] > 0) {
                return res;
            }
            if(i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int left = i + 1;
            int right = nums.length - 1;
            while(left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if(sum > 0) {
                    right --;
                }else if(sum < 0) {
                    left ++;
                }else {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    while(right > left && nums[left] == nums[left + 1]) {
                    left ++;
                }
                while(right > left && nums[right] == nums[right - 1]) {
                    right --;
                }
                left ++;
                right --;
                }

                
            }
        }
        return res;
    }
}

 

标签:right,Arrays,nums,++,三数,力扣,写题,int,left
From: https://www.cnblogs.com/akihi3174485976/p/17099870.html

相关文章