• 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     }
  • 相关阅读:
    Windows 和Linux 误删除后的恢复
    AWS 使用总结
    20180814 错误分析
    你必须知道的互联网协议详解
    linux常用命令和关闭防火墙
    Nginx之ngx_http_fastcgi_module模块详解
    nginx 限制ip
    nginx allow 多个ip & ipv4的网段表示方法解析
    从Nginx的Web请求处理机制中剖析多进程、多线程、异步IO
    剑指offer:二叉树的深度
  • 原文地址:https://www.cnblogs.com/feiling/p/3167395.html
Copyright © 2020-2023  润新知