zoukankan      html  css  js  c++  java
  • LintCode-三数之和

    题目描述:

      给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。

     注意事项

      在三元组(a, b, c),要求a <= b <= c。

      结果不能包含重复的三元组。

    样例

      如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:

      (-1, 0, 1)

      (-1, -1, 2)

     1 public class Solution {
     2     /**
     3      * @param numbers : Give an array numbers of n integer
     4      * @return : Find all unique triplets in the array which gives the sum of zero.
     5      */
     6     public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
     7         ArrayList<ArrayList<Integer>>  result = new ArrayList<ArrayList<Integer>>();
     8         if(numbers == null || numbers.length<3)
     9             return result;
    10         Arrays.sort(numbers);
    11         for(int i = 0;i<numbers.length; i++){
    12             int left = i+ 1;
    13             int right = numbers.length - 1;
    14             while(left < right){
    15                 int sum = numbers[i] + numbers[left] + numbers[right];
    16                 ArrayList<Integer> path = new ArrayList<Integer>();
    17                 if(sum==0){
    18                     path.add(numbers[i]);
    19                     path.add(numbers[left]);
    20                     path.add(numbers[right]);
    21                     if(result.contains(path)==false)
    22                         result.add(path);
    23                     left++;
    24                     right--;
    25                 }else if(sum>0){
    26                     right--;
    27                 }else{
    28                     left++;
    29                 }
    30             }
    31         }
    32        
    33         return result;
    34     }
    35 }
  • 相关阅读:
    【转载】实时嵌入式软件开发的25个常见错误
    软件测试高级测评师培训-白盒测试所用工具
    SQL update select语句
    JS对URL字符串进行编码/解码分析
    Java利用jacob实现文档格式转换
    Web打印--Lodop API
    常用正则表达式
    截取视频第一帧作为预览图片
    plupload api
    URL特殊字符的转义
  • 原文地址:https://www.cnblogs.com/xiaocainiao2hao/p/5364692.html
Copyright © 2011-2022 走看看