LeetCode算法入门- 3Sum -day9
- 题目描述:
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]
]
- 思路分析:
题目的意思是找到数组中所有3个和为0的数,并且不能重复。
该题可以转化成Two Sum的思路去解决。先固定一个数,然后从数组中剩下的数中查找和为该数负值(target)得2个数,则转化成了Two Sum问题:1. 先排序数组,使两个指针分别指向首尾的两个数,2. 如果这两个数和等于target,则找到,3. 如果小于target则右移左指针,如果大于target则左移右指针。
- 关键是题目要求去重,所以每次移动指针的时候要判断一下是否和上一个数相同,如果相同则继续移动。
代码如下:
class Solution {public List<List<Integer>> threeSum(int[] nums) {int len = nums.length;List<List<Integer>> result = new ArrayList<>();//记得先排序,这样才能够排除重复的答案Arrays.sort(nums);for(int i = 0; i < len; i++){//这里的i != 0的判断目的是为了i-1不越界if(i != 0 && nums[i] == nums[i - 1])//continue语法很少用,若条件满足,则不执行当次循环的代码,i要继续+1continue;int target = -nums[i];int left = i + 1;int right = len - 1;while(left < right){if(nums[left] + nums[right] == target){//Arrays.asList()这个方法是直接将元素添加到temp中去List<Integer> temp = Arrays.asList(nums[i],nums[left],nums[right]);result.add(temp);left++;right--;//去重同时记得判断left<rightwhile(left < right && nums[left] == nums[left-1])left++;while(left < right && nums[right] == nums[right+1])right--;}else if(nums[left] + nums[right] < target){left++;}else{right--;}}}return result;}
}