【Question】
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0
方法一:从头开始查找
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int len=nums.size();
for(int i=0;i<len;i++)
{
if (target==nums[i]) return i;
else if (target<nums[0]) return 0;
else if (target>nums[len-1]) return len;
else if (target>nums[i]&&target<nums[i+1]&&(i+1)<len) return i+1;
else {};
}
}
};
方法二:二分查找
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int len=nums.size();
int low =0;
int high=len-1;
int mid;
if (target<nums[0]) return 0;
else if(target>nums[len-1]) return len;
while(low<high)
{
mid = (low +high)/2;
if (target==nums[mid]) return mid;
else if (low+1==high) return high;
else if (target<nums[mid]) high=mid;
else if (target>nums[mid]) low=mid;
}
return low;
}
};