[leetcode]15. 3Sum三数之和

Given an array nums of n integers, are there elements abc in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

题意:

给定一个数组和一个值target,找出所有三数加起来等于target的组合。

思路:

以[-1, 0, 1, 2, -1, -4] 为例

先sort一下数组,保证ascening order,变为

[-4,         -1,      -1,     0,     1,     2]

  i (base)

                   j(left)                                                    k(right)

i 来遍历数组

j 和 k 向中间靠拢,用来查找其三数之和是否为target

注意几点:

1、题目要求“The solution set must not contain duplicate triplets.” 每次移动 i , j , k 都注意查重

2、Arrays工具类中常用方法需要牢记:

Arrays.sort() 排序数组

Arrays.fill() 填充数组

Arrays.toString() 将int数组转成string数组

Arrays.asList() 将数组转成list集合

代码:

 1     public List<List<Integer>> threeSum(int[] nums) {
 2         List<List<Integer>> result = new ArrayList<>();
 3         if (nums.length < 3) return result;
 4         Arrays.sort(nums);
 5         final int target = 0;
 6 
 7         for (int i = 0; i < nums.length - 2; ++i) {
 8             if (i > 0 && nums[i] == nums[i-1]) continue;
 9             int j = i+1;
10             int k = nums.length-1;
11             while (j < k) {
12                 if (nums[i] + nums[j] + nums[k] < target) {
13                     ++j;
14                     while(nums[j] == nums[j-1] && j < k) ++j;
15                 } else if(nums[i] + nums[j] + nums[k] > target) {
16                     --k;
17                     while(nums[k] == nums[k+1] && j < k) --k;
18                 } else {
19                     result.add(Arrays.asList(nums[i], nums[j], nums[k]));
20                     ++j;
21                     --k;
22                     while(nums[j] == nums[j-1] && j < k) ++j;
23                     while(nums[k] == nums[k+1] && j < k) --k;
24                 }
25             }
26         }
27         return result;
28     }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9124596.html
今日推荐