老汉技术专栏

Java开发程序猿一枚~欢迎各位批评指正

LintCode 57. 三数之和

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

public class Solution {
   /**
    * @param numbers: Give an array numbers of n integer
    * @return: Find all unique triplets in the array which gives the sum of zero.
    */
   public List<List<Integer>> threeSum(int[] numbers) {
      // write your code here
      List<List<Integer>> list = new ArrayList<>();
      if (numbers == null || numbers.length == 0) {
         return list;
      }
      Arrays.sort(numbers);
      for (int i = 0; i < numbers.length; i++) {
         int twoSum = 0 - numbers[i];
         for (int j = i + 1; j < numbers.length; j++) {
            int left = twoSum - numbers[j];
            for (int k = j + 1; k < numbers.length; k++) {
               if (numbers[k] == left) {
                  List<Integer> tmplist = new ArrayList<>();
                  tmplist.add(numbers[i]);
                  tmplist.add(numbers[j]);
                  tmplist.add(numbers[k]);
                  boolean flag = false;
                  for (int m = 0; m < list.size(); m++) {
                     if (tmplist.equals(list.get(m))) {
                        flag = true;
                     }
                  }
                  if (!flag) {
                     list.add(tmplist);
                  }
               }
            }
         }
      }
      return list;
   }
}

阅读更多
文章标签: java lintcode
个人分类: java开发
上一篇LintCode 56. 两数之和
下一篇LintCode 59. 最接近的三数之和
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭