
image.png
(图片来源https://leetcode-cn.com/problems/search-insert-position/
)
| 日期 | 是否一次通过 | comment |
|---|---|---|
| 2020-02-18 |
二分模板:
- sta+1<end
- mid = sta ; end = sta
public int searchInsert(int[] nums, int target) {
if(nums == null || nums.length < 1) {
return -1;
}
int sta = 0, end = nums.length - 1;
while(sta + 1 < end) {
int mid = sta + (end - sta)/2;
if(nums[mid] == target) {
return mid;
}
if(nums[mid] > target) {
end = mid;
} else {
sta = mid;
}
}
if(nums[sta] >= target) {
return sta;
} else if(nums[end] >= target) {
return end;
} else {
return end + 1;
}
}