当前位置:网站首页>And is two numbers of S - two questions per day
And is two numbers of S - two questions per day
2022-07-28 07:35:00 【Ink man bookworm】
The finger of the sword Offer 57. And for s Two numbers of
It's time to get up and brush questions every morning , It's really interesting to brush questions , Two questions a day , Come on ️

Enter an ascending array and a number s, Find two numbers in an array , So that their sum is exactly s. If the sum of many pairs of numbers is equal to s, Then output any pair .
Example 1:
Input :nums = [2,7,11,15], target = 9
Output :[2,7] perhaps [7,2]
Example 2:
Input :nums = [10,26,30,31,47,60], target = 40
Output :[10,30] perhaps [30,10]
Limit :
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
Ideas
Algorithm : Double pointer .
First, because ordered arrays , So the basic judgment is double pointer , Add the elements of the array corresponding to the left and right pointers ,
- Equal to the target array , Assign to array , return ,
Remember to return- Larger than the target array , The right pointer moves to the left
- Smaller than target array , The left pointer moves to the left
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;
边栏推荐
猜你喜欢
随机推荐
【无标题】
Introduction to magnetic ring selection and EMC rectification skills
Deeply analyze the implementation of singleton mode
【jvm优化超详细】常见的JVM调优场景
0727~面试题梳理
MySQL基础知识学习(二)
再次出现用户净流失,大失颜面的中国移动推出超低价套餐争取用户
Daily question - split equal sum subset
Pytorch extracts the feature map of a certain layer
最早截止时间优先(EDF)
Which of class A and class B is more stringent in EMC?
flowable工作流所有业务概念
深入剖析单例模式的实现
Student duty problems
和为s的两个数字——每日两题
[solution] visual full link log tracking - log tracking system
【干货】32个EMC标准电路分享!
Current limiting ratelimiter of guava
隔离级别RR、间隙锁、幻读
Mysql查看某个表所占内存大小









