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

来源:互联网 发布:矩阵张量积计算公式 编辑:程序博客网 时间:2024/06/17 05:16

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;elselow = mid + 1;}if (high < 0)return 0;if (low >= nums.size())return nums.size();return low;    }};




0 0
原创粉丝点击