-
Notifications
You must be signed in to change notification settings - Fork 0
/
191203-1.cpp
52 lines (50 loc) · 1014 Bytes
/
191203-1.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// https://leetcode-cn.com/problems/search-insert-position/
#include <cstdio>
#include <vector>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if (nums.empty()) return 0;
int n = nums.size();
const int* a = &nums[0];
if (target < a[0]) return 0;
if (target > a[n - 1]) return n;
int i = 0;
int j = n - 1;
while (i <= j) {
if (a[i] == target) return i;
if (a[j] == target) return j;
int k = (i + j) / 2;
if (k == i) return j;
if (a[k] == target) return k;
if (a[k] < target) {
i = k;
} else {
j = k;
}
}
return i;
}
};
int main()
{
Solution s;
{
vector<int> a = {1,3,5,6};
printf("%d\n", s.searchInsert(a, 5)); // answer: 2
}
{
vector<int> a = {1,3,5,6};
printf("%d\n", s.searchInsert(a, 2)); // answer: 1
}
{
vector<int> a = {1,3,5,6};
printf("%d\n", s.searchInsert(a, 7)); // answer: 4
}
{
vector<int> a = {1,3,5,6};
printf("%d\n", s.searchInsert(a, 0)); // answer: 0
}
return 0;
}