方法1(引入unordermap进行迭代判断):
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if(nums.size()==0)
{
return -1;
}
unordered_map<int,int> map;
int n = nums.size();
for(int i=0;i<n;++i)
{
map[nums[i]] = i;
}
if(map[target]&&n>1)
{
return map[target];
}
if(nums[0]==target)
{
return 0;
}
for(int i=0;i<n;i++)
{
if(nums[0]>target)
{
return map[nums[0]];
}
else if(nums[i]<target&&i+1<n&&nums[i+1]>target)
{
return i+1;
}
}
return n;
}
};
方法二:(二分查找)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
if(nums.size()==0)
{
return -1;
}
int left = 0;
int right = n;
while(left<right)
{
int mid = left+(right-left)/2;
if(nums[mid]<target)
{
left = mid + 1;
}
else{
right = mid;
}
}
return left;
}
};