problem
solution
option 1 - linear search
1 | class Solution { |
option 2 - binary search
- normal version
1 | class Solution { |
- left bound
1
2
3
4
5
6
7
8
9
10
11
12
13
14class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size(), l=0,r=n;
while(l<r){
int mid = l+(r-l)/2;
if(nums[mid] ==target) return mid;
else if(nums[mid] < target) l = mid+1;
else r = mid;
}
return l ;
}
};
analysis
- option 1
- time complexity
O(n)
- space complexity
O(1)
- time complexity
- option 2
- time complexity
O(logn)
- space complexity
O(1)
- time complexity