[array] leetcode - 35. Search Insert Position - Easy

leetcode – 35. Search Insert Position – Easy

descrition

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 1:
Input: [1,3,5,6], 0
Output: 0

解析

二分查找的实现。

code


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

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

        return ileft;
    }
};

int main()
{
    return 0;
}

作者:fanling999 链接:https://www.cnblogs.com/fanling999/

    原文作者:fanling999
    原文地址: https://www.cnblogs.com/fanling999/p/7841621.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞