我是靠谱客的博主 危机乐曲,这篇文章主要介绍15. 三数之和(java),现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组。 示例: 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/3sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:hash

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution { public List<List<Integer>> threeSum(int[] nums) { LinkedList<List<Integer>> result = new LinkedList<>(); Arrays.sort(nums); for(int i = 0; i < nums.length; i++) { if(nums[i] > 0) break; if(i-1 >= 0 && nums[i] == nums[i-1]) continue; Set<Integer> set2 = new HashSet<>(); int target = -nums[i]; for(int j = i+1; j < nums.length; j++){ int num = target - nums[j]; if(set2.contains(num)){ if(j+1 < nums.length && nums[j] == nums[j+1]) continue; LinkedList<Integer> list = new LinkedList<>(); result.add(Arrays.asList(nums[i],nums[j],num)); } set2.add(nums[j]); } } return result; } }

解法二:双指针

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

最后

以上就是危机乐曲最近收集整理的关于15. 三数之和(java)的全部内容,更多相关15.内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部