题目:
给出一个从小到大排号序的数组nums,给出一个int型的target,要求如果target在nums中,则返回target的索引,如果不在,则返回target应该插入的位置。
举例:(例子来源于https://leetcode.com/problems/search-insert-position/description/)
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 1:
Input: [1,3,5,6], 0
Output: 0
思路:
二分法
代码:
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
int searchInsert(vector<int>& nums, int target)
{
int length = nums.size();
if(length == 0) return 0;
if(target < nums[0]) return 0;
if(target > nums[length - 1]) return length;
int head = 0,tail = length,center;
while(head < tail)
{
center = (head + tail)/2;
if(nums[center] == target) return center;
if(nums[center] < target) head = center;
else tail = center;
if(head + 1 == tail)
{
if(nums[head] == target) return head;
else return tail;
}
}
}
int main()
{
vector<int> nums;
nums.push_back(1);
nums.push_back(3);
nums.push_back(5);
nums.push_back(6);
cout<<searchInsert(nums, 0)<<endl;
return 0;
}
时间复杂度:
O(logn)。
空间复杂度:
O(1)。