题目描述: LeetCode题目原地址
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.
给定一个包含n
个整数的数组nums
,判断nums
中是否存在三个元素a, b, c
,使得a + b + c = 0
?找到所有满足条件且不重复的三元组。
例如: 给定一个数组 nums = [-1, 0, 1, 2, -1, -4]
满足条件的方案为:
[
[-1, 0, 1],
[-1, -1, 2]
]
解法一: 三个数的和为指定数(即0),可以考虑先固定一个数nums[i]
,在剩下的数组中找两个数相加等于target = -nums[i]
的数即可,则问题转化为:求两个数之和为target
的数,很容易想到Two Sum这一题,用HashMap的求解,详细解答之前有过一篇博文。由于原文要求不可重复,可将HaspMap改成HashSet。
代码一:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new LinkedList<>();
Arrays.sort(nums);
for(int i = 0;i< nums.length-2;i++){
if(i > 0 && nums[i] == nums[i-1]) continue
twoSum(list, nums, i+1