LeetCode 35. Search Insert Position 搜尋插入位置
解法一:class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int i=0;
for(;i<nums.size();i++)
{
if(target==nums[i])
return i;
else if(target<nums[i])
break;
}
return i;
}
};
解法二:class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int low = 0, high = nums.size()-1;
while (low <= high) {
int mid = low + (high-low)/2;
if (nums[mid] < target)
low = mid+1; else
high = mid-1;
}
return low;
}
};