当前位置:网站首页>和为s的两个数字——每日两题
和为s的两个数字——每日两题
2022-07-28 05:32:00 【墨客小书虫】
剑指 Offer 57. 和为s的两个数字
又是每天早晨起来刷题的时候了,刷题真的太有意思了,每天两道题,一起加油哦️

输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]
示例 2:
输入:nums = [10,26,30,31,47,60], target = 40
输出:[10,30] 或者 [30,10]
限制:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
思路
算法:双指针。
首先因为有序数组,所以基本判断是双指针,左右指针对应数组的元素相加,
- 和目标数组相等,赋值到数组,返回,
记得返回- 比目标数组大,右指针往左移动
- 比目标数组小,左指针往左移动
int[] res = new int[2];
int left = 0;
int right = nums.length - 1;
int sum = 0;
while (left < right) {
sum = nums[left] + nums[right];
if (sum == target) {
res[0]=nums[left];
res[1]=nums[right];
return res;
} else if (sum > target) {
right--;
} else {
left++;
}
}
return res;
边栏推荐
- Redis哨兵模式及集群
- Detailed explanation of active scanning technology nmap
- C language review (modifier article)
- Gd32f407 porting freertos+lwip
- Qucs preliminary use guide (not Multism)
- Shell --- conditional statement practice
- js二级联动院系
- easypoi导出表格带echars图表
- Static and floating routes
- Easypoi one to many, merge cells, and adapt the row height according to the content
猜你喜欢
随机推荐
Add, delete, check and modify linked lists
GFS分布式文件系统
Log in to Oracle10g OEM and want to manage the monitor program, but the account password input page always pops up
Standard C language learning summary 7
Standard C language learning summary 5
shell---条件语句练习
N天前的日期
Codesensor: convert the code into AST and then into text vector
Eslint FAQ solutions collection
Blueberry pie Bluetooth debugging process
Pytorch installation - CPU version
Not used for the longest time recently
Easypoi one to many, merge cells, and adapt the row height according to the content
map使用tuple实现多value值
C语言详解系列——数组详解,一维数组、二维数组
根据excel生成create建表SQL语句
Rsync+inotify to realize remote real-time synchronization
删除链表中的节点——每日一题
Leetcode then a deep copy of the linked list
JS upload file method









