您的位置:首页 > 编程语言 > C语言/C++

LeetCode刷题(C++)——Search Insert Position(Easy)

2017-05-09 11:31 344 查看
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)从到到尾遍历数组,直到找到target或者找到第一个大于target的位置,返回该位置。时间复杂度为O(n)

class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if (nums.empty())
return 0;
int i = 0;
for (; i < nums.size();i++)
{
if (nums[i] == target||nums[i]>target)
return i;
}
return i;
}
};

(2)利用二分查找来确定是否存在target,如果存在返回该元素下标,如果不存在,返回查找结束的位置。注意两头边界时的特殊情况。

class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if (nums.empty())
return 0;
int low = 0, high = nums.size() - 1;
while (low <= high)
{
int mid = (low + high) >> 1;
if (nums[mid] == target)
return mid;
else if (nums[mid] > target)
high = mid - 1;
else
low = mid + 1;
}
if (high < 0)
return 0;
if (low >= nums.size())
return nums.size();
return low;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息