当前位置:网站首页>Leetcode (167) -- sum of two numbers II - input ordered array
Leetcode (167) -- sum of two numbers II - input ordered array
2022-06-28 14:30:00 【SmileGuy17】
Leetcode(167)—— Sum of two numbers II - Input an ordered array
subject
I'll give you a subscript from 1 The starting array of integers numbers , The array has been pressed Non decreasing order , Please find out from the array that the sum satisfying the addition is equal to the target number target Two numbers of . Let these two numbers be numbers[index1] and numbers[index2] , be 1 <= index1 < index2 <= numbers.length .
In length 2 Array of integers for [index1, index2] Returns the subscript of these two integers in the form of index1 and index2.
You can assume that each input Only corresponding to the only answer , And you Can not be Reuse the same elements .
The solution you design must use only constant level extra space .
Example 1:
Input :numbers = [2,7,11,15], target = 9
Output :[1,2]
explain :2 And 7 The sum is equal to the number of targets 9 . therefore index1 = 1, index2 = 2 . return [1, 2] .
Example 2:
Input :numbers = [2,3,4], target = 6
Output :[1,3]
explain :2 And 4 The sum is equal to the number of targets 6 . therefore index1 = 1, index2 = 3 . return [1, 3] .
Example 3:
Input :numbers = [-1,0], target = -1
Output :[1,2]
explain :-1 And 0 The sum is equal to the number of targets -1 . therefore index1 = 1, index2 = 2 . return [1, 2] .
Tips :
- 2 2 2 <= numbers.length <= 3 ∗ 1 0 4 3 * 10^4 3∗104
- − 1000 -1000 −1000 <= numbers[i] <= 1000 1000 1000
- numbers Press Non decreasing order array
- − 1000 -1000 −1000 <= target <= 1000 1000 1000
- There is only one valid answer
Answer key
This problem can be used 「1. Sum of two numbers 」 Solution method , Use O ( n 2 ) O(n^2) O(n2) Time complexity and O ( 1 ) O(1) O(1) The space complexity is solved violently , Or with a hash table O ( n ) O(n) O(n) Time complexity and O ( n ) O(n) O(n) To solve the space complexity of . But both of them are for unordered arrays , It doesn't take advantage of the ordered nature of the input array . Using the ordered property of input array , We can get the solution with better time complexity and space complexity .
Method 1 : Double pointer
Ideas
Initially, two pointers point to the position of the first element and the position of the last element . Calculate the sum of two elements pointed to by two pointers at a time , And compare with the target value . If the sum of the two elements is equal to the target value , The only solution is found . If the sum of the two elements is less than the target value , Then move the left pointer to the right one bit . If the sum of the two elements is greater than the target value , Move the right pointer to the left by one bit . After moving the pointer , Repeat the above operation , Until you find the answer .
The essence of using double pointers is Narrow the search . Then will the possible solutions be filtered out ? The answer is no .
prove : hypothesis numbers [ i ] + numbers [ j ] = target \textit{numbers}[i]+\textit{numbers}[j]=\textit{target} numbers[i]+numbers[j]=target It's the only solution , among 0 ≤ i < j ≤ numbers . length − 1 0 \leq i<j \leq \textit{numbers}.\textit{length}-1 0≤i<j≤numbers.length−1. Initially, the two pointers point to the subscript 0 0 0 And subscripts numbers . length − 1 \textit{numbers}.\textit{length}-1 numbers.length−1, The left pointer points to a subscript less than or equal to i i i, The right pointer points to a subscript greater than or equal to j j j. Unless the left and right pointers are already in the subscript i i i and j j j, Otherwise, the left pointer must reach the subscript first i i i The position or right pointer reaches the subscript first j j j The location of .
- Suppose the left pointer reaches the subscript first i i i The location of , Then the right pointer is still subscript j j j The right side of the , numbers [ i ] + numbers [ j ] > target \textit{numbers}[i]+\textit{numbers}[j]>\textit{target} numbers[i]+numbers[j]>target, Therefore, the right pointer must move to the left , The left pointer cannot be moved to i i i The right side of the .
- Suppose the right pointer reaches the subscript first j j j The location of , Then the left pointer is still subscript i i i The left side of the , numbers [ i ] + numbers [ j ] < target \textit{numbers}[i]+\textit{numbers}[j]<\textit{target} numbers[i]+numbers[j]<target, Therefore, the left pointer must move to the right , The right pointer cannot move to j j j The left side of the .
thus it can be seen , Throughout the movement , The left pointer cannot be moved to i i i The right side of the , The right pointer cannot move to j j j The left side of the , Therefore, possible solutions will not be filtered out . Because the question ensures that there is a unique answer , Therefore, the answer can be found by using double pointers .
Code implementation
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int size = numbers.size();
vector<int> ans{
1, 2};
if(size == 2) return ans;
int n = 0, m = size-1; // Double pointer , Reverse traversal
while(true){
if(numbers[m] + numbers[n] > target) m--;
else if(numbers[m] + numbers[n] < target) n++;
else break;
}
ans[0] = n+1;
ans[1] = m+1;
return ans;
}
};
Complexity analysis
Time complexity : O ( n ) O(n) O(n), among n n n Is the length of the array . The maximum total number of times two pointers move is n n n Time , That is, you can traverse the array at most , The worst case is that the two numbers to be found are adjacent .
Spatial complexity : O ( 1 ) O(1) O(1)
边栏推荐
- Rslo: self supervised lidar odometer (real time + high precision, icra2022)
- Reverse a stack with recursive functions and stack operations only
- @Controlleradvice + @exceptionhandler handles controller layer exceptions globally
- js 判断字符串为空或者不为空
- 2022中式烹调师(高级)试题及在线模拟考试
- Mulan open work license 1.0 open to the public for comments
- Youju new material rushes to Shenzhen Stock Exchange: it plans to raise 650million yuan, with an annual revenue of 333million yuan
- How to count dimensions of foreign trade E-mail Promotion
- Foreign trade SEO Webmaster Tools
- Validate palindrome string
猜你喜欢

Ionq and Ge research confirmed that quantum computing has great potential in risk aggregation

Dry goods | how to calculate the KPI of scientific researchers, and what are the h index and G index

名创优品通过上市聆讯:寻求双重主要上市 年营收91亿

Youju new material rushes to Shenzhen Stock Exchange: it plans to raise 650million yuan, with an annual revenue of 333million yuan

Ding! Techo day Tencent technology open day arrived as scheduled!

开源社邀您参加OpenInfra Days China 2022,议题征集进行中~

从小小线虫谈起——溯源神经系统进化,开启生命模拟

A bug liver a week I can't help mentioning issue

智联招聘基于 Nebula Graph 的推荐实践分享

叮!Techo Day 腾讯技术开放日如约而至!
随机推荐
Single responsibility principle
Leetcode(665)——非递减数列
Rails进阶——框架理论认知与构建方案建设(一)
RAM ROM FLASH的区别
运行近20年,基于Win 98的火星探测器软件迎来首次升级
Which securities company is the largest and safest? How to open an account is the safest
智联招聘基于 Nebula Graph 的推荐实践分享
Robot range of motion (DFS)
加油站(贪心)
机器人的运动范围(DFS)
Flutter series: offstage in flutter
Rails advanced -- framework theory cognition and construction scheme construction (I)
单一职责原则
Ionq and Ge research confirmed that quantum computing has great potential in risk aggregation
【数字IC精品文章收录】近500篇文章|学习路线|基础知识|接口|总线|脚本语言|芯片求职|安全|EDA|工具|低功耗设计|Verilog|低功耗|STA|设计|验证|FPGA|架构|AMBA|书籍|
Only four breakthrough Lenovo smart Summer Palace in mainland China won the "IDC Asia Pacific Smart City Award in 2022"
A queue of two stacks
ArcGIS vector center point generates rectangle and cuts TIF image for deep learning sample training
Go array and slice, []byte to string[easy to understand]
仅用递归函数和栈操作逆序一个栈