-
Notifications
You must be signed in to change notification settings - Fork 0
/
35.cpp
36 lines (34 loc) · 829 Bytes
/
35.cpp
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
class Solution
{
public:
int searchInsert(vector<int> &nums, int target)
{
if (nums.size() == 0)
return 0;
if (nums[0] > target)
return 0;
int len = nums.size();
if (nums[len - 1] < target)
return len;
int left = 0, right = len - 1;
while (true)
{
int mid = (left + right) / 2;
if (target == nums[mid])
return mid;
else if (target < nums[mid])
{
if (target > nums[mid - 1])
return mid;
right = mid - 1;
}
else
{
if (target < nums[mid + 1])
return mid + 1;
left = mid + 1;
}
}
return -1;
}
};