前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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
public class Solution {
public int searchInsert(int[] nums, int target) {
if(nums[0] >= target) return 0;
if(nums[nums.length - 1] == target) return nums.length - 1;
if(nums[nums.length - 1] < target) return nums.length;
int l = 0, r = nums.length - 1,mid = 0;
while(r -l > 1){
mid = (r+l)/2;
if(nums[mid] < target) l = mid;
else if(nums[mid] > target ) r = mid;
else break;
}
if(nums[mid] == target) return mid;
else return r;
}
}