lintcode-60-搜索插入位置
60-搜索插入位置
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。样例
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0挑战
O(log(n)) time
标签
数组 排序数组 二分法
思路
采用二分查找
code
class Solution {
/**
* param A : an integer sorted array
* param target : an integer to be inserted
* return : an integer
*/
public:
int searchInsert(vector<int> &A, int target) {
// write your code here
int low = 0, high = A.size()-1, size = A.size(), mid = (low+high)/2;
if(size <= 0) {
return 0;
}
while(low <= high) {
if(A[mid] == target) {
return mid;
}
else if(A[mid] > target) {
high = mid - 1;
mid = (low+high)/2;
}
else {
low = mid + 1;
mid = (low+high)/2;
}
}
if(A[mid] > target) {
return mid-1>0 ? mid-1: 0;
}
else if(A[mid] < target) {
return mid+1;
}
}
};