您的位置:首页 > 其它

leetcode 35:Search Insert Position

2015-10-17 22:08 447 查看
题目:

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
思路:
其实像这种只要是排好序的查找,基本思路都是在二分法查找基础上做变化。本题也是这样,不过以前没找到的话,返回-1,即

if(low>high) return -1;

现在返回的就是low或者是high了,也是比较简单,时间复杂度:O(lgn)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int size = nums.size();
if (size == 0) return 0;
return binary(nums, 0, size - 1, target);
}

int binary(vector<int>&array, int low, int high, int key)
{
if (low > high)
{
return low;
}
int mid = (low + high) / 2;

if (array[mid] == key)
return mid;
else if (array[mid] < key)
return binary(array, mid + 1, high, key);
else
return binary(array, low, mid - 1, key);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: