当前位置:网站首页>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)
边栏推荐
- Ionq and Ge research confirmed that quantum computing has great potential in risk aggregation
- A bug liver a week I can't help mentioning issue
- 2022中式烹調師(高級)試題及在線模擬考試
- 如何设计数据可视化平台
- js 判断字符串为空或者不为空
- Introduction to common components of IOT low code platform
- 原生JS 实现页面元素的拖动 拖拽
- Practice of constructing ten billion relationship knowledge map based on Nebula graph
- Numbers that only appear once
- IonQ联合GE Research证实:量子计算在风险聚合上有巨大潜力
猜你喜欢

Votre Code parle? (1)

sort

推荐四款可视化工具,解决 99% 的可视化大屏项目!

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

外贸SEO 站长工具

叮!Techo Day 腾讯技术开放日如约而至!

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

优巨新材冲刺深交所:拟募资6.5亿 年营收3.33亿

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

Talking from the little nematode -- tracing the evolution of nervous system and starting life simulation
随机推荐
Cat dog queue
Can your code talk? (upper)
干货 | 科研人的KPI怎么算,H指数和G指数是什么
VPS是干嘛用的?有哪些知名牌子?与云服务器有什么区别?
力扣解法汇总522-最长特殊序列 II
2022金属非金属矿山安全检查(地下矿山)复训题库及在线模拟考试
基于ASP的勤工俭学管理系统
推荐四款可视化工具,解决 99% 的可视化大屏项目!
Multi dimensional monitoring: the data base of intelligent monitoring
CVPR disputes again: IBM's Chinese draft papers were accused of copying idea, who won the second place in the competition
Talking from the little nematode -- tracing the evolution of nervous system and starting life simulation
机器人的运动范围(DFS)
正则匹配数字,英文以及英文符号
A queue of two stacks
Leetcode(406)——根据身高重建队列
NPOI导出Excel并下载到客户端
IonQ联合GE Research证实:量子计算在风险聚合上有巨大潜力
Rslo: self supervised lidar odometer (real time + high precision, icra2022)
【二叉树】在二叉树中分配硬币
@Controlleradvice + @exceptionhandler handles controller layer exceptions globally