zoukankan      html  css  js  c++  java
  • LeetCode OJ

    题目:

    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)

    解题思路:

      先将数组排序。 然后分别固定第一个元素为num[0], num[n]。 用2Sum的方法找剩下的两个数。

    代码:

     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
     3         Arrays.sort(num);
     4         ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
     5         for (int first = 0; first < num.length;) {
     6             int left = first + 1, right = num.length - 1;
     7             while (left < right) {
     8                 int sum = num[first] + num[left] + num[right];
     9                 if (sum == 0) {
    10                     ArrayList<Integer> cur_ans = new ArrayList<Integer>();
    11                     cur_ans.add(num[first]); cur_ans.add(num[left]); cur_ans.add(num[right]);
    12                     ans.add(cur_ans);
    13                     left++; right--;
    14                 } else if (sum > 0) {
    15                     right --;
    16                 } else {
    17                     left ++;
    18                 }
    19                 while (left < right && (left != first+1 && num[left] == num[left-1])) left ++; // delete duplicate triplets
    20                 while (left < right && (right != num.length-1 && num[right] == num[right+1])) right --;// delete duplicate triplets
    21             }
    22             for (first++; first < num.length && num[first] == num[first-1]; first ++);// delete duplicate triplets
    23         }
    24         return ans;
    25     }
    26 }
  • 相关阅读:
    css中单位的使用
    css中max-width和min-width的应用
    css-样式初始化
    html中map标签和area标签的应用
    html中常见的小问题(1)
    防止图片被盗用
    关于thinkphp的__construct和_initialize
    禁用cookie后如何使用session还有session_id的使用
    is_null(self::$_instance) && self::$_instance = new self();
    echo、print、print_r、printf、sprintf、var_dump的区别
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3788790.html
Copyright © 2011-2022 走看看