-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSumII-InputArrayIsSorted.cpp
More file actions
42 lines (37 loc) · 1.08 KB
/
Copy pathtwoSumII-InputArrayIsSorted.cpp
File metadata and controls
42 lines (37 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Source : https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
// Author : https://github.com/xinsheng
// Date : 2021-11-27
/*
* Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order,
* find two numbers such that they add up to a specific target number.
* Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
*/
#include <string.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
* Idea:
* Add two number from both side of vector, and move cursor depends on the two numbers sum.
*/
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size()-1;
int i = 0;
while (i < n) {
if ((numbers[i] + numbers[n]) > target) {
n--;
}
else if ((numbers[i] + numbers[n]) < target) {
i++;
}
else {
break;
}
}
vector<int> ans = {i+1,n+1};
return ans;
}
};