class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if(nums[0]>target) return 0;
if(nums[nums.size()-1]<target) return nums.size();
int left = 0;
int right = nums.size()-1;
int mid =(left+right)/2;
while(left<=right){
if(nums[mid]== target) return mid;
else if(nums[mid]<target) left = mid+1;
else if(nums[mid]>target) right =mid-1;
}
return mid+1;
}
};
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int lens = nums.size();
int left = 0;
int right = lens-1;
if(nums[left]>target) return 0;
if(nums[right]<target) return lens;
while(left<=right){
int mid =(left+right)/2;
if(nums[mid]== target) return mid;
else if(nums[mid]<target) left = mid+1;
else if(nums[mid]>target) right =mid-1;
}
return right+1;
}
};
求数组那里应该是耗时了,求了两次