zoukankan      html  css  js  c++  java
  • 3 Sum 解答

    Question

    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)

    Solution

    First, we sort the array and then implement 2 pointers to get 2 Sum. Time complexity is O(n2)

    Notice here, we need to consider duplicates in result.

     1 public class Solution {
     2     public List<List<Integer>> threeSum(int[] nums) {
     3         if (nums == null || nums.length < 1)
     4             return null;
     5         Arrays.sort(nums);
     6         int length = nums.length;
     7         List<List<Integer>> result = new ArrayList<List<Integer>>();
     8         for (int i = 0; i <= length - 3; i++) {
     9             // Remove duplicates
    10             if (i > 0 && nums[i] == nums[i - 1])
    11                 continue;
    12             int target = 0 - nums[i];
    13             int l = i + 1, r = length - 1;
    14             while (l < r) {
    15                 if (nums[l] + nums[r] == target) {
    16                     result.add(Arrays.asList(nums[i], nums[l], nums[r]));
    17                     while (l < r && nums[l] == nums[l+1]) l++;
    18                     while (l < r && nums[r] == nums[r-1]) r--;
    19                     l++;
    20                     r--;
    21                 } else if (nums[l] + nums[r] < target) {
    22                     l++;
    23                 } else {
    24                     r--;
    25                 }
    26             }
    27         }
    28         return result;
    29     }
    30 }
  • 相关阅读:
    vue表单验证定位到错误的地方
    INSPINIA Version 2.5 Bootstrap3
    volatile 彻底搞懂
    solr6.4.2之webservice兼容升级
    快速排序
    Elasticsearch调优篇 10
    TCP 连接为什么需要 3 次握手和 4 次挥手
    搜索技术与方案的选型与思考
    Elasticsearch调优篇 09
    Elasticsearch调优篇 08
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4890807.html
Copyright © 2011-2022 走看看