zoukankan      html  css  js  c++  java
  • leetcode -- 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:

    • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ? b ? c)
    • 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)
     

     [Some tricks]
    1. Line 18 and Line 23.
        filter the duplicate during two-pointer scan. For example [-2, 0, 0, 2,2], the expected output should be [-2,0,2]. If no filter here, the output will be duplicate as [-2,0,2] and [-2,0,2]
    2. Line 31-33
       filter the duplicate for outside iteration. For example [-2, -2, -2, 0,2].

     1 public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
     2         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
     3         Arrays.sort(num);
     4         int length = num.length;
     5         for(int i = 0; i < length; i++){
     6             int start = i + 1;
     7             int end = length - 1;
     8             int target = 0 - num[i];
     9             while(start < end){
    10                 if(target == num[start] + num[end]){
    11                     ArrayList<Integer> list = new ArrayList<Integer>();
    12                     list.add(num[i]);
    13                     list.add(num[start]);
    14                     list.add(num[end]);
    15                     result.add(list);
    16                     start ++;
    17                     end --;
    18                     while(num[start] == num[start - 1] && start < end){
    19                         start ++;
    20                     }
    21                     while(num[end] == num[end + 1] && start < end){
    22                         end --;
    23                     }
    24                 } else if(target > num[start] + num[end]){
    25                     start ++;
    26                 } else {
    27                     end --;
    28                 }
    29             }
    30             
    31             while ((i < length - 1) && num[i] == num[i + 1]) {
    32                 i++;
    33             } 
    34         }
    35         return result;
    36     }
  • 相关阅读:
    抽奖系统 random()
    JavaScript 稀奇的js语法
    Node初识笔记 1第一周
    vue 自定义指令
    vue 组件 单选切换控制模板 v-bind-is
    学习网址
    vue 组件 子向父亲通信用自定义方法用事件监听
    vue 组件 模板中根数据绑定需要指明路径并通信父
    vue 组件 模板input双向数据数据
    测试样式
  • 原文地址:https://www.cnblogs.com/feiling/p/3167395.html
Copyright © 2011-2022 走看看