当前位置:网站首页>和为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;
边栏推荐
- VNC Timed out waiting for a response from the computer
- Joern's code uses -devign
- Addition, deletion, check and modification of sequence table
- 最近最久未使用
- Insert sort of sort
- Circular linked list problem
- Softmax multi classification gradient derivation
- Review of C language (variable parameters)
- Shell--- function
- freemarker合并单元格,if、else标签的使用,null、空字符串处理
猜你喜欢

MHA高可用配置及故障切换

Rsync+inotify to realize remote real-time synchronization

MySQL excludes holidays and calculates the date difference

Understanding of maximum likelihood estimation, gradient descent, linear regression and logistic regression
C语言详解系列——数组详解,一维数组、二维数组

“核弹级” Log4j 漏洞仍普遍存在,并造成持续影响

easypoi导出隔行样式设置

Continous Gesture Recognition with hand-orented spatiotemporal feature

Shell -- first day homework

一口气学完4种 Redis 集群方案,真是各有千秋
随机推荐
rsync+inotify实现远程实时同步
Two horizontal and vertical screen switching schemes for uniapp mobile terminal
build_ opencv.sh
freemarker合并单元格,if、else标签的使用,null、空字符串处理
Rsync+inotify to realize remote real-time synchronization
JS secondary linkage Department
C language review (modifier article)
Short work priority SJF
最早截止时间优先(EDF)
如何理解CMS回收器降低gc停顿时间
ThreadLocal那些事
guava之Retryer
GFS distributed file system
一口气学完4种 Redis 集群方案,真是各有千秋
List of papers on gestures
C language address book system
A timed task reminder tool
Learning to estimate 3D hand pose from single RGB image & amp notes
ESLint常见问题解决方案集锦
Add, delete, check and modify linked lists