LeetCode算法系列:35. Search Insert Position

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82152044

题目描述:

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 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 4:

Input: [1,3,5,6], 0
Output: 0

算法实现:

具体算法和前面几个问题的本质是相同的,还是采用二分法,只不过如果找不到目标元素,最后i,j指向的位置也正好是target能够插入的位置(target能够插入j和i最终位置中间,即i的位置)

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        if(nums.empty()) return 0;
        if(target < nums[0])return 0;
        if(target > nums.back()) return nums.size();
        int i = 0, j = nums.size() - 1, k;
        while(i <= j){
            k = int((i + j)/2);
            if(nums[k] == target)return k;
            else if(nums[k] > target) j = k - 1;
            else i = k + 1;
        }
        return i;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/82152044