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)从到到尾遍历数组,直到找到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;
}
};
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;
}
};
相关文章推荐
- [LeetCode] 035. Search Insert Position (Medium) (C++)
- 【C++】【LeetCode】35. Search Insert Position
- [LeetCode] 035. Search Insert Position (Medium) (C++)
- LeetCode 35 — Search Insert Position(C++ Java Python)
- LeetCode之Search Insert Position(C++)
- LeetCode-Easy部分中标签为Array#35: Search Insert Position
- leetcode_c++:Search insert position(035)
- [C++]LeetCode: 41 Search Insert Position
- LeetCode - Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- [leetcode刷题系列]Search Insert Position
- Leetcode: Search Insert Position
- LeetCode: Search Insert Position
- LeetCode_Search Insert Position
- Search Insert Position [LEETCODE]
- [LeetCode] Search Insert Position
- Leetcode::Search Insert Position
- leetcode Search Insert Position
- [Leetcode 23] 35 Search Insert Position