Skip to content

Commit 212b1b9

Browse files
committed
Update 167. Two Sum II - Input array is sorted.cpp
1 parent edfe827 commit 212b1b9

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

167. Two Sum II - Input array is sorted.cpp

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,18 @@
11
class Solution {
22
public:
33
vector<int> twoSum(vector<int>& numbers, int target) {
4-
const size_t n = numbers.size();
4+
int left = 0, right = numbers.size() - 1;
55
vector<int> res;
6-
int left, right, mid, sum;
7-
for(int i = 0; i < n; ++i){
8-
left = i + 1, right = n - 1;
9-
while(left <= right){
10-
mid = (left + right) / 2;
11-
sum = numbers[i] + numbers[mid];
12-
if(sum == target){
13-
res.push_back(i + 1);
14-
res.push_back(mid + 1);
15-
return res;
16-
}else if(sum < target)
17-
left = mid + 1;
18-
else right = mid - 1;
19-
}
6+
while(left < right){
7+
long long val = numbers[left] + numbers[right];
8+
if(val == target){
9+
res.push_back(left + 1);
10+
res.push_back(right + 1);
11+
break;
12+
}else if(val < target)
13+
left++;
14+
else
15+
right--;
2016
}
2117
return res;
2218
}

0 commit comments

Comments
 (0)