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     }
  • 相关阅读:
    Codeforces 512E
    UOJ #36 -【清华集训2014】玛里苟斯(线性基+暴搜)
    Codeforces 1188E
    洛谷 P7163
    C++ Boost库 操作日期与时间
    C/C++ 搜索缝隙并插入ShellCode
    线性代数学习之正交性,标准正交矩阵和投影
    洛谷 P5851 [USACO19DEC]Greedy Pie Eaters P(区间dp)
    洛谷 [NOIP2009 普及组] 道路游戏(dp)
    洛谷 P2890 [USACO07OPEN]Cheapest Palindrome G(区间dp)
  • 原文地址:https://www.cnblogs.com/feiling/p/3167395.html
Copyright © 2011-2022 走看看