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 }
  • 相关阅读:
    软件测试原则
    java知识点
    jquery取值
    Javaweb命名规则
    @ResponseBody
    jquery ajax 方法及各参数详解
    @RequestMapping用法详解
    eclipse+android+opencv环境搭建的步骤
    Java中的内部类(回调)
    OpenCV直方图(直方图、直方图均衡,直方图匹配,原理、实现)
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4890807.html
Copyright © 2011-2022 走看看