1 Star 0 Fork 0

Neo_1001/LeetCode刷题记录

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
LC_15v2.java 1.37 KB
一键复制 编辑 原始数据 按行查看 历史
Neo_1001 提交于 2024-04-10 22:16 . first commit
package LeetCode;
import java.util.*;
public class LC_15v2 {
public static void main(String[] args) {
int[] nums = {-1, 0, 1, 2, -1, -4};
System.out.println(threeSum(nums));
}
public static List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
if (nums.length < 3) return res;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
if (nums[i] + nums[left] + nums[right] == 0) {
ArrayList<Integer> res_tmp = new ArrayList<>();
Collections.addAll(res_tmp, nums[i], nums[left], nums[right]);
res.add(res_tmp);
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
right--;
}else if (nums[i] + nums[left] + nums[right] > 0) right--;
else if (nums[i] + nums[left] + nums[right] < 0) left++;
}
}
return res;
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/neo1001/leet-code-practice-record.git
git@gitee.com:neo1001/leet-code-practice-record.git
neo1001
leet-code-practice-record
LeetCode刷题记录
master

搜索帮助