您的位置:首页 > 其它

Leetcode-search-insert-position

2016-06-27 17:45 435 查看


题目描述

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

拿到题目,映入脑海中就是而非查找,找到就return位置,找不到就从头到尾找到合适插入的位置,于是乎,这是我的代码:

public class Solution {
public int searchInsert(int[] A, int target) {
int start = 0;
int end = A.length-1;
boolean isFound = false;
while(start <= end){
int mid = (start+end) / 2;
if(A[mid] == target){
isFound = true;
return mid;
}else if(A[mid] > target){
end = mid-1;
}else{
start = mid+1;
}
}
if(!isFound){
if(target<A[0]){
return 0;
}else if(target > A[A.length-1]){
return A.length;
}else{
for(int i=1; i<A.length; i++){
if(A[i-1] < target && A[i] > target){
return i;
}
}
}
}
return 0;
}
}

但是,发现找合适插入位置的方法不对,应该是最后停下来的start位置就是我们要return的位置。

public static int searchInsert(int[] A, int target) {

int start = 0;
int end = A.length-1;
while(start <= end){
int mid = (start+end) / 2;
if(A[mid] == target){
return mid;
}else if(A[mid] > target){
end = mid-1;
}else{
start = mid+1;
}
}
return start;
}
但是当我点开别人这样的代码的时候

public class Solution {
public int searchInsert(int[] A, int target) {
for(int i=0;i<A.length;i++)
{
if(target<=A[i])
return i;
}
return A.length;
}
}
我觉得我自己就是智障! 因为原数组是排好序的,找到大于等于target的位置就是我们想要return的位置呀!哎,看到这个代码,我很尴尬。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: