zoukankan      html  css  js  c++  java
  • Leetcode: 3Sum

    Given an array S of n integers, are there elements a, b, c 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)

    Best 做法:不用Extra Space, Time Complexity still O(N^2)

    Good syntax:

    List<List<Integer>> res = new LinkedList<>();

    res.add(Arrays.asList(num[i], num[lo], num[hi]));

     // creating Arrays of String type
    
    
     String a[] = new String[] { "A", "B", "C", "D" };
                
     // getting the list view of Array
    
    
     List<String> list = Arrays.asList(a);
     
     1 class Solution {
     2     public List<List<Integer>> threeSum(int[] nums) {
     3         List<List<Integer>> res = new ArrayList<> ();
     4         if (nums == null || nums.length < 3) return res;
     5         Arrays.sort(nums);
     6         
     7         int p = nums.length - 1;
     8         while (p >= 2) {
     9             if (p < nums.length - 1 && nums[p] == nums[p + 1]) {
    10                 p--;
    11                 continue;
    12             }
    13             int target = -nums[p];
    14             int l = 0, r = p - 1;
    15             while (l < r) {
    16                 if (nums[l] + nums[r] == target) {
    17                     res.add(Arrays.asList(nums[l], nums[r], nums[p]));
    18                     while (l < r && nums[l] == nums[l + 1]) {
    19                         l++;
    20                     }
    21                     while (l < r && nums[r] == nums[r - 1]) {
    22                         r--;
    23                     }
    24                     l++;
    25                     r--;
    26                 }
    27                 else if (nums[l] + nums[r] < target) {
    28                     l++;
    29                 }
    30                 else r--;
    31             }
    32             p--;
    33         }
    34         return res;
    35     }
    36 }
  • 相关阅读:
    LDAP+Jenkins
    LDAP+SASL+SVN
    Ubuntu下的LDAP服务搭建
    LDAP+Confluence
    LDAP+Nextcloud
    vim -d
    linux默认编辑器
    vim相关调优
    MySQL中的保留字
    RHEL7配置ip地址
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4010951.html
Copyright © 2011-2022 走看看