当前位置:网站首页>2022.07.22 _ a day
2022.07.22 _ a day
2022-07-31 07:42:00 【No. い】
15. 三数之和
题目描述
给你一个包含 n
个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0
且不重复的三元组.
注意:答案中不可以包含重复的三元组.
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
- 数组
- 双指针
- 排序
coding
// May heaven not need to be heavy、、、
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums.length < 3) {
return res;
}
Arrays.sort(nums);
for (int first = 0; first < nums.length; first ++) {
if (nums[first] > 0) {
break;
}
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
int second = first + 1;
int third = nums.length - 1;
while (second < third) {
if (nums[second] + nums[first] + nums[third] == 0) {
res.add(Arrays.asList(new Integer[]{
nums[first], nums[second], nums[third]}));
while (second < third && nums[second] == nums[second + 1]) {
second ++;
}
while (second < third && nums[third] == nums[third - 1]) {
third --;
}
second ++;
third --;
}else if (nums[second] + nums[first] + nums[third] < 0) {
second ++;
} else {
third --;
}
}
}
return res;
}
}
边栏推荐
- Foreign trade website optimization - foreign trade website optimization tutorial - foreign trade website optimization software
- 2022.07.12_每日一题
- Run the NPM will pop up to ask "how are you going to open this file?"
- LeetCode:952. 按公因数计算最大组件大小【欧拉筛 + 并查集】
- 【Go报错】go go.mod file not found in current directory or any parent directory 错误解决
- 测试 思维导图
- 毫米波技术基础
- 关于求反三角函数的三角函数值
- 文件 - 07 删除文件: 根据fileIds批量删除文件及文件信息
- 熟悉而陌生的新朋友——IAsyncDisposable
猜你喜欢
随机推荐
mysql的建表语句_三种常用的MySQL建表语句
shell之条件语句(test、if、case)
Leetcode952. 按公因数计算最大组件大小
【解决】mysql本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止
【微服务】(十六)—— 分布式事务Seata
Kubernetes调度
解决安装 Bun 之后出现 zsh compinit: insecure directories, run compaudit for list. Ignore insecure directorie
2022.07.29_每日一题
【Go语言入门教程】Go语言简介
【Star项目】小帽飞机大战(七)
事务的传播机制
金融租赁业务
单点登录 思维导图
那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
嵌入式系统驱动初级【2】——内核模块下_参数和依赖
Foreign trade website optimization - foreign trade website optimization tutorial - foreign trade website optimization software
2022.07.15_Daily Question
2022.07.13_每日一题
MySQL详解
postgresql源码学习(33)—— 事务日志⑨ - 从insert记录看日志写入整体流程