Skip to content

Latest commit

 

History

History

0015

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Description

Given an array nums of n integers, are there elements a, b, c 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] ] 

Tags: Array, Two Pointers

思路

题意是让你从数组中找出所有三个和为 0 的元素构成的非重复序列,这样的话我们可以把数组先做下排序,然后遍历这个排序数组,用两个指针分别指向当前元素的下一个和数组尾部,判断三者的和与 0 的大小来移动两个指针,其中细节操作就是优化和去重。

classSolution { publicList<List<Integer>> threeSum(int[] nums) { List<List<Integer>> list = newArrayList<>(); intlen = nums.length; if (len < 3) returnlist; Arrays.sort(nums); intmax = nums[len - 1]; if (max < 0) returnlist; for (inti = 0; i < len - 2; ) { if (nums[i] > 0) break; if (nums[i] + 2 * max < 0) { while (nums[i] == nums[++i] && i < len - 2) ; continue; } intleft = i + 1, right = len - 1; while (left < right) { intsum = nums[i] + nums[left] + nums[right]; if (sum == 0) { list.add(Arrays.asList(nums[i], nums[left], nums[right])); while (nums[left] == nums[++left] && left < right) ; while (nums[right] == nums[--right] && left < right) ; } elseif (sum < 0) ++left; else --right; } while (nums[i] == nums[++i] && i < len - 2) ; } returnlist; } }

结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:awesome-java-leetcode

close