• 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 }
  • 相关阅读:
    方法参数个数最多不宜超过4个
    避免方法中使用大量局部变量
    JQuery学习备忘
    CSS学习备忘
    解析Path方法备忘
    获取差集合的一种实现思路
    前台JSP页面独立化
    requireJs的使用
    handlebar
    移动端h5<a>标签点击样式去除
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4010951.html
Copyright © 2020-2023  润新知