-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInsertPosition.cpp
More file actions
37 lines (36 loc) · 965 Bytes
/
SearchInsertPosition.cpp
File metadata and controls
37 lines (36 loc) · 965 Bytes
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
#include <iostream>
#include <vector>
class Solution {
public:
int searchInsert(std::vector<int>& nums, int target) {
if(target > nums.back()) {
return nums.size();
}
if(target < nums.front()) {
return 0;
}
int lower, upper, current, val, narrowed;
lower = 0;
upper = nums.size() - 1;
current = (upper-lower)/2;
val = nums[current];
while(val != target) {
current = (upper+lower)/2;
if(upper-lower < 2) {
nums[current] < target ? current++ : current = current;
return current;
}
val = nums[current];
if(target > val) {
lower = current;
}
else if(target < val) {
upper = current;
}
else {
return current;
}
}
return current;
}
};