-
Notifications
You must be signed in to change notification settings - Fork 0
/
35. Search Insert Position
99 lines (80 loc) · 2.06 KB
/
35. Search Insert Position
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const int ZERO = [](){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
class Solution {
public:
int searchInsert3(const vector<int>& nums, int target)
{
int left = 0, right = nums.size() - 1, mid = 0;
while(left <= right)
{
mid = (left + right) / 2;
if(target > nums[mid])
{
left = mid + 1;
}
else if(target < nums[mid])
{
right = mid - 1;
}
else
{
return mid;
}
}
return mid + (target > nums[mid]);
}
int searchInsert2(const vector<int>& nums, int target)
{
int from = 0, size = int(nums.size());
for(int j = size >> 1; j >= 1; j = j >> 1)
{
while(from + j < size && target >= nums[from + j])
{
from += j;
}
}
return from + (target > nums[from]);
}
int searchInsert1(const vector<int>& nums, int target)
{
int index = 0, first = 0, step = 0, count = nums.size();
while(count)
{
index = first;
step = count >> 1;
index += step;
if(nums[index] < target)
{
first = ++index;
count -= step + 1;
}
else
{
count = step;
}
}
return first;
}
// left - позиция элемента < target
// right - позиция элемента >= target
int searchInsert(const vector<int>& nums, int target)
{
int left = -1, right = nums.size(), mid = 0;
while(right - left > 1)
{
mid = left + ((right - left) >> 1);
if(nums[mid] < target)
{
left = mid;
}
else
{
right = mid;
}
}
return right;
}
};