题目:
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
Subscribe to see which companies asked this question.
注意点:①使用java进行编写时,类名与方法名固定,不可修改。
②不需要编写main函数,只要符合算法逻辑即可
③可以调用部分现有的函数,如:Arrays.binarySearch(nums, target);
解答:
1. 语言:java
法一:
public class Solution {
public int searchInsert(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
//若为 <,则会造成结果错误
while(start <= end){
//防止溢出
int mid = (end - start) / 2 + start;
if(target == nums[mid]){
return mid;
}else if(target < nums[mid]){
//若写为end = mid;则会造成超时
end = mid - 1;
}else if(target > nums[mid]){
start = mid + 1;
}
}
return start;
}
}
法二:调用方法
public class Solution {
public int searchInsert(int[] nums, int target) {
int pos = Arrays.binarySearch(nums, target);
if(pos < 0){
//说明target不存在,此时返回第一个大于target的位置
return -pos - 1;
}else{
return pos;
}
}
}
2. 语言:Python
转载于:https://my.oschina.net/liyurong/blog/877599