首页 > 其他 > 详细

15. 3Sum

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!