当前位置:网站首页>LeetCode Exercise - Two Questions About Finding Sum of Array Elements
LeetCode Exercise - Two Questions About Finding Sum of Array Elements
2022-07-30 18:15:00 【SK_Jaco】
1. 数组中和为 0 的三个数
1.1 题目描述
给定一个已按照 升序排列 的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target .
函数应该以长度为 2 的整数数组的形式返回这两个数的下标值.numbers 的下标 从 0 开始计数 ,所以答案数组应当满足 0 <= answer[0] < answer[1] < numbers.length .
假设数组中存在且只存在一对符合条件的数字,同时一个数字不能使用两次.
示例 1:
输入:numbers = [1,2,4,6,10], target = 8
输出:[1,3]
解释:2 与 6 之和等于目标数 8 .因此 index1 = 1, index2 = 3 .
示例 2:
输入:numbers = [2,3,4], target = 6
输出:[0,2]
示例 3:
输入:numbers = [-1,0], target = -1
输出:[0,1]
1.2 解题思路与代码
1.2.1 解题思路
This question is to find if there are two numbers in an array that are equal to a given number,It can be considered that there is a brute force solution to traverse the array in two layers and sum it up in turn,But the same time complexity is O(n^2) 太高了.The title has stipulated that the array is an array sorted in ascending order,We can use the double pointer to move from both sides to the middle to calculate the sum of the numbers pointed to by the two pointers,再与 target Make a comparison move.First let the left pointer l Pointer 0 位置,右指针 r 指向数组最后一位,Then calculate the sum of the numbers pointed to by the two pointers,At this time, the calculated sum will appear in the following three cases:
- 如果和等于 target 退出循环并返回 l 和 r(Because the question stipulates that there is only one answer)
- 如果和小于 target,Because the array is sorted from small to large,At this point, move the left pointer to the right to make the sum of the two numbers larger
- Similarly if and greater than target,Now move the right pointer to the left,This makes the sum of the two numbers smaller
以题目示例 numbers = [1,2,4,6,10], target = 8 为例进行图解:
首先让 l 和 r 指向首位,此时 l 和 r The sum of the pointing numbers is 11,大于 target ,因此让 r 左移
r 左移之后,此时 l=0,r=3,两数之和为 7 ,小于 target 于是让 l 右移
l 右移之后,此时 l=1,r=3,两数之和为 8 ,等于 target 满足题意返回 [1, 3]
1.2.2 代码
class Solution {
public int[] twoSum(int[] numbers, int target) {
int l = 0;
int r = numbers.length - 1;
int[] ans = new int[2];
while (l < r) {
if (numbers[l] + numbers[r] == target) {
ans[0] = l;
ans[1] = r;
break;
} else if (numbers[l] + numbers[r] < target) {
l++;
} else {
r--;
}
}
return ans;
}
}
1.2.3 测试结果
通过测试
2. 数组中和为 0 的三个数
2.1 题目描述
剑指 Offer II 007. 数组中和为 0 的三个数
给定一个包含 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]
输出:[]
2.2 解题思路与代码
2.2.1 解题思路
This question is actually the same as the one above,Just from the sum of the two numbers target The sum of three numbers becomes zero.我们可以转换一下思想,If we grab a number in an array num,Then it is programmed to find the sum of the two numbers in the remaining numbers -num.我们在进一步,对数组 nums 进行排序,Then we traverse the array from left to right:
- 遍历第一位 nums[0] 时,我们就需要在 [1, n-1] Find the sum of two numbers equal to -num[0]
- Traverse to the second position nums[1] 时,我们就需要在 [2, n-1] Find the sum of two numbers equal to -num[1]
- Traverse to the third position nums[2] 时,我们就需要在 [3, n-1] Find the sum of two numbers equal to -num[2]
…… - 依次类推
Since we have already sorted the array,Then the numbers in the following search range are sorted in ascending order,Here you can see that it is exactly the same as the above question,只不过 target 变成了 -nums[i],查找范围变成 [i+1, n-1].从上面的分析,We can loop through the array in the outer layer,A double pointer slave is used inside the loop [i+1, n-1] Find the sum of two numbers equal to -num[i] 的两个数.Same topic as above,也有三种情况:
- When the sum of the two numbers is less than -num[i] 时,l 右移
- 当两数之和大于 -num[i] 时,l 左移
- 当两数之和等于 -num[i] 时,i、l、r The numbers in the three positions are put into the result list,然后 l 右移、r 左移.
这里需要注意,The title requires that no repeated numbers appear,因此当 nums[i] 等于 nums[i-1] 时,跳过本次循环,同理 nums[l] 等于 nums[l-1]、 nums[r] 等于 nums[r+1] also needs to be skipped.下面是数组 [-1,0,1,2,-1,-4] 查找的过程,首先 i=0,我们使用 l 和 r 在 [1, 5] Find the sum of two numbers equal to 4 的两个数,当 l 等于 r When the inner loop is launched.然后 i=1 此时在 [2, 5] Find the sum of two numbers equal to 1 此时 l=2 和 r=5 The sum of the two numbers referred to is equal to 1 满足条件,放入结果数组中.Then repeat the above process,直到数组遍历完成.
2.2.2 代码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
if (nums.length == 0) {
return ans;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int target = -nums[i];
int l = i + 1;
int r = nums.length - 1;
while (l < r) {
if (nums[l] + nums[r] == target) {
ans.add(Arrays.asList(nums[i], nums[l], nums[r]));
do {
l++;
} while (l < r && nums[l] == nums[l - 1]);
do {
r--;
} while (l < r && nums[r] == nums[r + 1]);
} else if (nums[l] + nums[r] < target) {
l++;
} else {
r--;
}
}
}
return ans;
}
}
2.2.3 测试结果
通过测试
3.总结
- The first question is handled using double pointers,The sum of the two numbers is less than the target,左指针右移;大于目标,右指针左移;等于目标,Exit the loop to return the result
- The second question is a variant of the first question,排序后遍历数组,The same is to find the sum of two numbers equal to a certain number in the following array
- The second question needs to be de-duplicated,Hence three pointers i、l、r If after the move is equal to the number before the move,Then need to keep moving
边栏推荐
- 软件测试13年从业经验的前辈,总结的5条测试就业建议....
- Mo Team - Elegant Violence
- Network Basics (3) 01-Basic Concepts of Networks - Protocols, Host Addresses, Paths and Parameters of URL Addresses & 127.0.0.1 Local Loopback Address & View URL IP Address and Access Ping Space + URL
- What is NDT equipment?
- 基础架构之Mongo
- One year after graduation, I was engaged in software testing and won 11.5k. I didn't lose face to the post-98 generation...
- 【开发者必看】【push kit】推送服务典型问题合集3
- Redis for infrastructure
- A senior with 13 years of experience in software testing, summed up 5 test employment suggestions....
- [Solved] The problem that Unity Hub fails to obtain a license or does not respond and cannot develop
猜你喜欢

图解LeetCode——11. 盛最多水的容器(难度:中等)

宽带射频放大器OA4SMM4(1)

【HMS core】【Analytics Kit】【FAQ】如何解决华为分析付费分析中付款金额显示为0的问题?

【网络工程】A、B、C、D、E类IP地址划分依据和特殊的IP地址

Pytorch基础--tensorboard使用(一)

5分钟搞懂MySQL - 行转列

Pagoda builds PHP adaptive lazy website navigation source code measurement

OSPF详解(4)

沃尔沃中国的年中总结,在“安全感”中寻找未来

微博广告分布式配置中心的构建与实践(有彩蛋)
随机推荐
《自然语言处理实战入门》---- 文本样本扩展小技巧:使用回译技术进行样本增强
LayaBox---TypeScript---变量声明
Application of time series database in the field of ship risk management
线性筛求积性函数
while,do while,for循环语句
The sixteenth issue of eight-part article Balabala said (MQ)
千亿级、大规模:腾讯超大 Apache Pulsar 集群性能调优实践
(2022杭电多校四)1001-Link with Bracket Sequence II(区间动态规划)
LayaBox---TypeScript---泛型
This year..I sincerely recommend the professional engineer to upgrade to the book!
MySQL中的存储过程(详细篇)
5 个开源的 Rust Web 开发框架,你选择哪个?
终端分屏工具Terminalx的使用
这玩意儿都能优化?果然是细节都在魔鬼里。
数据库系统原理与应用教程(067)—— MySQL 练习题:操作题 82-89(十一):数据的增、删、改操作
CCNA-子网划分(VLSM)
莫队--优雅的暴力
今年这情况。。真心推荐专科的工程师升个本!
【HarmonyOS】【ARK UI】HarmonyOS ets语言怎么实现双击返回键退出
[OC study notes] attribute keyword