• 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     }
  • 相关阅读:
    css选择器以及块级元素、行内元素
    拒绝服务(DOS/DDOS/DRDOS)
    分布式拒绝服务攻击(DDoS)原理及防范
    不可不知 DDoS的攻击原理与防御方法(2)
    重写与隐藏
    VMWare虚拟机centos7安装redis
    APP微信支付Java后台的实现(springmvc)
    hbm2java和hbm2ddl工具
    Hibernate主键生成策略
    Oracle常用数据类型
  • 原文地址:https://www.cnblogs.com/feiling/p/3167395.html
Copyright © 2020-2023  润新知