码迷,mamicode.com
首页 > 其他好文 > 详细

15. 3Sum

时间:2017-10-16 09:41:58      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:color   style   return   div   nts   logs   i++   cat   length   

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: 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]
]
 1     public List<List<Integer>> threeSum(int[] nums) {
 2         Arrays.sort(nums);
 3         List<List<Integer>> res = new LinkedList<>();
 4         for (int i = 0; i < nums.length; i++) {
 5             if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {
 6                 int low = i + 1, high = nums.length - 1;
 7                 while (low < high) {
 8                     if (nums[i] + nums[low] + nums[high] == 0) {
 9                         res.add(Arrays.asList(nums[i], nums[low], nums[high]));
10                         while (low < high && nums[low] == nums[low + 1]) low++;
11                         while (low < high && nums[high] == nums[high - 1]) high--;
12                         low++;
13                         high--;
14                     } else if (nums[i] + nums[low] + nums[high] > 0) high--;
15                     else low++;
16                 }
17             }
18         }
19         return res;      
20     }

 

15. 3Sum

标签:color   style   return   div   nts   logs   i++   cat   length   

原文地址:http://www.cnblogs.com/wzj4858/p/7675381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!