您的位置:首页 > 其它

[刷题]Search Insert Position

2015-04-07 22:01 218 查看
[LintCode]Search Insert Position

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) {
// 2015-4-7 binary search
if (A == null || A.length == 0) {
return 0;
}

int start = 0;
int end = A.length - 1;

while (start + 1 < end) {
int mid = (start + end) / 2;
if (A[mid] >= target) {
end = mid;
} else {
start = mid;
}
}

if (A[start] >= target) {
return start;
} else if (A[end] >= target) {
return end;
} else {
return end + 1;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: