-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0035-search-insert-position.cpp
More file actions
61 lines (58 loc) · 1.42 KB
/
0035-search-insert-position.cpp
File metadata and controls
61 lines (58 loc) · 1.42 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <vector>
using namespace std;
class Solution
{
public:
int searchInsert(vector<int> &nums, int target)
{
int low = 0, high = nums.size() - 1;
int res = -1;
int index = (low + high) / 2;
if(target > nums[high]) {
return high+1;
} else if (target < nums[0]) {
return 0;
}
while (low <= high)
{
if (nums[index] == target)
{
res = index;
break;
}
else if (nums[index] > target)
{
high = index - 1;
if(nums[index-1] < target) {
res = index;
break;
}
}
else
{
low = index + 1;
if(nums[index+1] > target) {
res = index+1;
break;
}
}
index = low + (high - low) / 2;
}
return res;
}
};
int main()
{
vector<int> vec;
vec.push_back(-5);
vec.push_back(-2);
vec.push_back(1);
vec.push_back(4);
vec.push_back(9);
vec.push_back(15);
int res = (new Solution())->searchInsert(vec, 1);
res = (new Solution())->searchInsert(vec, -7);
res = (new Solution())->searchInsert(vec, 3);
res = (new Solution())->searchInsert(vec, 9);
res = (new Solution())->searchInsert(vec, 10);
}