Description

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.

Example

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, 二分查找
  • 思路2,线性
  • 线性跑出来比二分快一倍。这测试用例。。

代码

  • 二分
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int len = nums.size();
        if(len == 0) return 0;
        
        int low = 0, high = len - 1, mid = 0;
        
        while(low <= high){
            mid = low + (high - low) / 2;
            
            if(nums[mid] == target) return mid;
            else if(nums[mid] > target) high = mid - 1;
            else low = mid + 1;
        }
        
        return low;
    }
};
  • 线性
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int len = nums.size();
        if(len == 0) return 0;
        
        int i = 0;
        for(i = 0; i < len; ++i){
            if(nums[i] >= target)
                return i;
        }
        return i;
    }
};
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程

4811 0元 限免