zoukankan      html  css  js  c++  java
  • 15. 3Sum

    Given an array nums of n integers, are there elements abc in nums 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.

    Example:

    Given array nums = [-1, 0, 1, 2, -1, -4],
    
    A solution set is:
    [
      [-1, 0, 1],
      [-1, -1, 2]
    ]


     1 class Solution {
     2     public List<List<Integer>> threeSum(int[] nums) {
     3         int n = nums.length;
     4         Arrays.sort(nums);
     5         List<List<Integer>> ans = new LinkedList<>();
     6         for (int i = 0; i < n - 2; ++i) {
     7             if (i == 0 || nums[i] != nums[i - 1]) {
     8                 int sum = 0 - nums[i];
     9                 int l = i + 1, r = n - 1;
    10                 while (l < r) {
    11                     if (nums[l] + nums[r] == sum) {
    12                         ans.add(Arrays.asList(nums[i], nums[l], nums[r]));
    13                         while (l + 1 <= r && nums[l] == nums[l + 1])l++;
    14                         while (r - 1 >= l && nums[r] == nums[r - 1])r--;
    15                         l++;
    16                         r--;
    17                     } else if (nums[l] + nums[r] < sum) {
    18                         l++;
    19                         
    20                     } else {
    21                         r--;
    22                     }
    23                 }
    24             } 
    25             
    26         }
    27         return ans;
    28     }
    29 }
  • 相关阅读:
    Tomcat安装和使用
    mysql5.7.18安装配置
    Memcached安装与使用
    Redis
    nginx的安装与使用
    python操作mysql
    Paramiko模块
    协程与异步IO
    Queue与生产者消费者模型
    C# 生成验证码 方法二
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12298593.html
Copyright © 2011-2022 走看看