# Search Insert Position

112人阅读 评论(0)

#### 容易 搜索插入位置

29%

[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) {
int low = 0;
int high = nums.length-1;
while(low < high){
int mid = low + (high - low)/2;
if(target > nums[mid]){
low = mid + 1;
}else if(target < nums[mid]){
high = mid -1;
}else{
return mid;
}
}
if(target > nums[low]){
return low+1;
}else{
return low;
}

}
}

lintcode:

public class Solution {
/**
* param A : an integer sorted array
* param target :  an integer to be inserted
* return : an integer
*/
public int searchInsert(int[] A, int target) {
int start = 0;
int end = A.length - 1;
int mid;

if(A==null || A.length == 0){
return 0;
}
if (target < A[0]) {
return 0;
}
// find the last number less than target
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (A[mid] == target) {
return mid;
} else if (A[mid] < target) {
start = mid;
} else {
end = mid;
}
}
//target一共有4种大小，=start,>start,=end,>end
if (A[end] < target) {
return end + 1;
}
if (A[end] == target) {
return end;
}
if (A[start] < target) {
return start + 1;
}
return start;
}
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：38545次
• 积分：2572
• 等级：
• 排名：第14776名
• 原创：221篇
• 转载：41篇
• 译文：0篇
• 评论：0条
文章分类