解析
时间复杂度要求,所以使用二分的思想,漏掉了很多问题,这里记录
- 在left-right=1时,已经找到了插入位置,但是没有赋值,然后break,所以导致一直死循环。
if(right - left == 1){ result = right; break; }
- 在和最右侧数比较时,漏掉了相等时就直接找到,所以在数组是[1,3],target=1时,应该返回下标0
if(target <= nums[left]){ result = left; break; }
- 长度为0时,不进入循环了,所以循环条件是left <= right。
代码
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0;
int right = nums.size()-1;
int result = 0;
while(left <= right){
int mid = (left+right)/2;
if(target <= nums[left]){
result = left;
break;
}
if( nums[right] < target){
result = right+1;
break;
}
if( nums[right] == target){
result = right;
break;
}
if(right - left == 1){
result = right;
break;
}
if(nums[mid] < target){
left = mid;
}else if(target < nums[mid]){
right = mid;
}else if(nums[mid] == target){
result = mid;
break;
}
}
return result;
}
};