-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution035.cpp
More file actions
48 lines (43 loc) · 904 Bytes
/
solution035.cpp
File metadata and controls
48 lines (43 loc) · 904 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
38
39
40
41
42
43
44
45
46
47
48
/**
* Search Insert Position
* Binary search algorith.
*
* cpselvis([email protected])
* September 8th, 2016
*/
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int lower = 0, upper = nums.size() - 1;
while (lower < upper)
{
int mid = (lower + upper) >> 1;
if (nums[mid] < target)
{
lower = mid + 1;
}
else if (nums[mid] > target)
{
upper = mid - 1;
}
else
{
return mid;
}
}
return nums[lower] < target ? lower + 1 : lower;
}
};
int main(int argc, char **argv)
{
int arr[4] = {1, 3, 5, 6};
vector<int> nums(arr + 0, arr + 4);
Solution s;
cout << s.searchInsert(nums, 5) << endl;
cout << s.searchInsert(nums, 2) << endl;
cout << s.searchInsert(nums, 7) << endl;
cout << s.searchInsert(nums, 0) << endl;
}