zoukankan      html  css  js  c++  java
  • [LeetCode] 15. 3Sum ☆☆

    Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

    Note: The solution set must not contain duplicate triplets.

    For example, given array S = [-1, 0, 1, 2, -1, -4],
    
    A solution set is:
    [
      [-1, 0, 1],
      [-1, -1, 2]
    ]

    解法:

      首先对原数组进行排序,然后开始遍历排序后的数组,这里注意不是遍历到最后一个停止,而是到倒数第三个就可以了,中间如果遇到跟前一个数相同的数字就直接跳过。对于遍历到的数,如果大于0则跳到下一个数,因为三个大于0的数相加不可能等于0;否则用0减去这个数得到一个sum,我们只需要再之后找到两个数之和等于sum即可,这样一来问题又转化为了求two sum,这时候我们一次扫描,找到了等于sum的两数后,加上当前遍历到的数字,按顺序存入结果中即可,然后还要注意跳过重复数字。时间复杂度为 O(n2)。代码如下:

    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();  // 注意不能是new List<>(); List是接口
            
            if (nums == null || nums.length < 3) {
                return res;
            }
            
            Arrays.sort(nums);
            for (int i = 0; i < nums.length - 2; i++) {
                if (nums[i] > 0) {
                    break;
                }
                if (i > 0 && nums[i] == nums[i - 1]) {
                    continue;
                }
                
                int sum = -nums[i];
                int left = i + 1, right = nums.length - 1;
                
                while (left < right) {
                    if (nums[left] + nums[right] == sum) {
                        ArrayList<Integer> triplet = new ArrayList<>();
                        triplet.add(nums[i]);
                        triplet.add(nums[left]);
                        triplet.add(nums[right]);
                        res.add(triplet);
                        
                        while (left < right && nums[left++] == nums[left]) {}
                        while (left < right && nums[right--] == nums[right]) {}
                        
                    } else if (nums[left] + nums[right] < sum) {
                        while (left < right && nums[left++] == nums[left]) {}
                        
                    } else {
                        while (left < right && nums[right--] == nums[right]) {}
                    }
                }
            }
            return res;
        }
    }
  • 相关阅读:
    Django模板
    创建我的第一个django项目
    python django环境配置与安装
    python第九期学习笔记(装饰器进阶)
    python第九期学习笔记(十二)(线程)
    python第九期学习笔记(装饰器)
    python第九期学习笔记(闭包)
    python第九期学习笔记(十二)(面向对象)
    python第九期学习笔记(十一)(面向对象)
    python第九期学习笔记(十)(模块)
  • 原文地址:https://www.cnblogs.com/strugglion/p/6407867.html
Copyright © 2011-2022 走看看