美文网首页
2022-03-04 「15. 三数之和」

2022-03-04 「15. 三数之和」

作者: 柠香萌萌鸡 | 来源:发表于2022-03-03 09:48 被阅读0次

今天勇敢牛牛挑战中等题啦:https://leetcode-cn.com/problems/3sum/
打开题目的时候偷瞄到标签有「双指针」,所以开始思路就比较正确,想到的是排序后用前后指针方式来遍历,减少时间复杂度。
但是确实没有考虑到题解中的难点:去重。
所以反复提交了4次才把题目解完,这题没有太多自己独特的想法,就直接贴标准思路吧。

双指针+排序+去重

代码题解:

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans= new ArrayList<>();
        // 先做异常情况处理
        int len = nums.length;
        if (nums == null || len < 3) {
            return ans;
        }

        Arrays.sort(nums);

        // 遍历数组,左右指针去重处理
        for(int i=0;i<len-1;i++) {
            if(nums[i]>0){
                break;
            }
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int L=i+1;
            int R=len-1;
            while (L<R) {
                int sum = nums[i] + nums[L] + nums[R];
                if (sum == 0) {
                    ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
                    while( L<R && nums[L] == nums[L+1]) {
                        L++;
                    }
                    while( L<R && nums[R] == nums[R-1]) {
                        R--;
                    }
                    L ++;
                    R --;
                }
                else if (sum < 0) {
                    L++;
                }
                else if (sum > 0) {
                    R--;
                }
            }
        }
        return ans;
    }
}

相关文章

网友评论

      本文标题:2022-03-04 「15. 三数之和」

      本文链接:https://www.haomeiwen.com/subject/hvbprrtx.html