当前位置:网站首页>Sum of three numbers: (sort + double pointer + pruning)
Sum of three numbers: (sort + double pointer + pruning)
2022-07-23 10:15:00 【Jingle!】
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
//1. Sort the array first : Sorting algorithm can be used here : Quick sort 、 Merge sort .
Arrays.sort(nums);
//2. Double pointer , One from the front , One from the back
for (int i = 0; i < nums.length; i++) {
// After sorting, if the first element is greater than zero , So no combination can make up a triple , Just return the result directly
if (nums[i] > 0) {
return res;
}
// Pruning operation : The first element is de duplicated ;(i > 0 To prevent index exceptions )
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
// Skip all duplicate values
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
// Find out , Correction and contraction at the same time
right--;
left++;
} else if (sum > 0) {
right--;
} else {
left++;
}
}
}
return res;
}边栏推荐
- 2.判断语句
- A brief tutorial for soft exam system architecture designer | requirements engineering
- How to build and use redis fragment cluster
- Ten years of sharpening a sword, the core technology evolution of the cloud native distributed database polardb-x
- 【循环语句】
- L-半胱氨酸修饰的金纳米粒子(Cys-GNPs)和牛血清白蛋白/生物素化白蛋白纳米粒
- Open source Invoicing system, 10 minutes to complete, it is recommended to collect!
- Error msb4181: the "qtrunwork" task returned false, but no error was recorded
- Earning power "needs to be accumulated
- 60 open-ended test questions, recite them and get a pay rise directly
猜你喜欢
随机推荐
九张图纵观加密市场周期规律
[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (VII)
【汇总篇】
图文并茂演示小程序movable-view的可移动范围
ssm框架外卖订餐系统
新的项目实现的技术点如有需要可以指导
Decompile the jar package / class file / modify the jar package using the decompile plug-in of idea
系统安全测试要怎么做,详细来说说
网络通信原理与IP地址的分配原理,网络七层由下往上分别为物理层、数据链路层、网络层、传输层、会话层、表示层和应用层
Time series dataset: power transformer dataset (etdataset)
SSH超市进销存管理系统
three文档使用
如何在OneFlow中新增算子
【C语言基础】16 可变数组(数组长度可扩展)
Multi-UA V Cooperative Exploringfor the Unknown Indoor EnvironmentBased on Dynamic Target Tracking翻译
Data middle office, Bi business interview (III): how to choose the right interviewees
Can Huatai Securities open an account online? Is it safe
这个工具,补齐了 JMeter性能分析最后一公里短板
Ten years of sharpening a sword, the core technology evolution of the cloud native distributed database polardb-x
Seven sorts -- detailed explanation of ten thousand words









