双指针类型
链接:三数之和
算法思路
- 算法回忆:需要不重复三元组。首先考虑到将数组进行排序,对排序后的数组进行指针遍历。接下来就是如何遍历的问题,遍历中考虑去除重复。我使用的是用HashMap统计字符使用过的次数,当找到/未找到以当前元素为起点的解时,需要考虑到,下次以下一个不重复的元素为新的起点。题解则使用双指针,第一个元素从左遍历,第二个在第一个右侧,第三个左侧。
- 模板代码如下:
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
Map<Integer,Integer> map = new HashMap<>();
for (int num : nums) {
if (map.containsKey(num)) {
map.replace(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
List<List<Integer>> ret = new ArrayList<>();
for (int i=0;i<nums.length-2;i++){
map.replace(nums[i],map.get(nums[i])-1);
for (int j=i+1;j<nums.length-1;j++){
List<Integer> ans = new ArrayList<>();
int temp = -(nums[i]+nums[j]);
map.replace(nums[j],map.get(nums[j])-1);
if (map.containsKey(temp)&&map.get(temp)>0&&temp>=nums[j]){
ans.add(nums[i]);
ans.add(nums[j]);
ans.add(temp);
ret.add(ans);
}
map.replace(nums[j],map.get(nums[j])+1);
while(j<nums.length-2&&nums[j]==nums[j+1]){
j++;
};
}
map.replace(nums[i],map.get(nums[i])+1);
while(i<nums.length-3&&nums[i]==nums[i+1]){
i++;
}
}
return ret;
}
}
题解:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// 枚举 a
for (int first = 0; first < n; ++first) {
// 需要和上一次枚举的数不相同
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
// c 对应的指针初始指向数组的最右端
int third = n - 1;
int target = -nums[first];
// 枚举 b
for (int second = first + 1; second < n; ++second) {
// 需要和上一次枚举的数不相同
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
// 需要保证 b 的指针在 c 的指针的左侧
while (second < third && nums[second] + nums[third] > target) {
--third;
}
// 如果指针重合,随着 b 后续的增加
// 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if (second == third) {
break;
}
if (nums[second] + nums[third] == target) {
List<Integer> list = new ArrayList<Integer>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
ans.add(list);
}
}
}
return ans;
}
}
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/3sum/solution/san-shu-zhi-he-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。