当前位置:网站首页>哈希——15. 三数之和
哈希——15. 三数之和
2022-07-24 11:23:00 【向着百万年薪努力的小赵】
1 题目描述
- 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
2 题目示例
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
3 题目提示
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
4 思路
暴力法的时间复杂度Q是O(n^3)。可以先固定一个值,然后寻找后两个值时可采取双指针的方法,将总的时间复杂度优化到O(n²)。
实现的过程中,要注意优化以及去重。
首先我们先对原数组进行排序,这样可以把重复的值集中到一起,便于去重。
确定第一个元素时,如果它已经比0大了,那么可以直接跳出循环,因为后面的数字都比它大。如[1,2,3,4], i = 0, nums[i]> 0,这样是不可能产生合法的情况的,直接break。
确定第一个元素时,如果发现它与它前面的值一样,那么跳过本轮。如[-1,-1,0,1],在第一轮后,已经选出了{-1,0,1},现在i=1, nums[i] == nums[ i - 1],为了避免重复,直接continue。
接下来利用双指针,left 指向i+1, right指向nums.length -1。逐个进行判断,并注意去重。
复杂度分析
·时间复杂度:o(N2),其中N是数组nums的长度。
·空间复杂度:O(log N)。我们忽略存储答案的空间,额外的排序的空间复杂度为O(log N)。然而我们修改了输入的数组nums,在实际情况下不—定允许,因此也可以看成使用了一个额外的数组存储了nums的副本并进行排序,空间复杂度为O(N)。
5 我的答案
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
// 总时间复杂度:O(n^2)
List<List<Integer>> ans = new ArrayList<>();
if (nums == null || nums.length <= 2) return ans;
Arrays.sort(nums); // O(nlogn)
for (int i = 0; i < nums.length - 2; i++) {
// O(n^2)
if (nums[i] > 0) break; // 第一个数大于 0,后面的数都比它大,肯定不成立了
if (i > 0 && nums[i] == nums[i - 1]) continue; // 去掉重复情况
int target = -nums[i];
int left = i + 1, right = nums.length - 1;
while (left < right) {
if (nums[left] + nums[right] == target) {
ans.add(new ArrayList<>(Arrays.asList(nums[i], nums[left], nums[right])));
// 现在要增加 left,减小 right,但是不能重复,比如: [-2, -1, -1, -1, 3, 3, 3], i = -2, left = 1, right = 6, [-2, -1, 3] 的答案加入后,需要排除重复的 -1 和 3
left++; right--; // 首先无论如何先要进行加减操作
while (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 {
// nums[left] + nums[right] > target
right--;
}
}
}
return ans;
}
}
另一种写法
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;
}
}
边栏推荐
- 在线客服聊天系统源码_美观强大golang内核开发_二进制运行傻瓜式安装_附搭建教程
- 【Golang】golang实现发送微信服务号模板消息
- The solution of permission denied
- Ask n! How many zeros are there behind
- Altium one key automatic BOM
- Lanqiao cup provincial training camp - stack and recursion
- 性能测试总结(一)---基础理论篇
- How to go from functional testing to automated testing?
- How to choose sentinel vs. hystrix current limiting?
- Sorting out the ideas of data processing received by TCP server, and the note of select: invalid argument error
猜你喜欢

聊聊软件测试-自动化测试框架

Jmeter-Runtime控制器

Only "a little bit", why do developers look up to you?

Video playback | how to become an excellent reviewer of international journals in the field of Geoscience and ecology?

Self taught software testing talent -- not covered

自学软件测试天赋异禀——不是盖的

08【AIO编程】

iMeta观点 | 短读长扩增子测序是否适用于微生物组功能的预测?

Lanqiao cup provincial training camp - stack and recursion

网络爬虫之短信验证
随机推荐
Why can't memset initialize array elements to 1?
Idea hidden Idea folder hides.Iml files
Leetcode 112. 路径总和
有关并行的两个重要定律
Installing Oracle Xe with Linux
【Golang】golang中map元素的删除和清空
Altium one key automatic BOM
【Golang】golang实现post请求发送form类型数据函数
Directional crawling Taobao product name and price (teacher Songtian)
RRPN:Arbitrary-Oriented Scene Text Detection via Rotation Proposals
【C】 Understanding C language variable scope and life cycle from memory
Ask n! How many zeros are there behind
【Golang】golang实现sha256加密函数
07 [use of path and files classes]
Lanqiao cup provincial training camp - stack and recursion
How to use SSH and SFTP protocols at home
Druid encryption command
Decomposition of kubernets principle
Xilinx FPGA soft core development process
自学软件测试天赋异禀——不是盖的