Search insertion position binary search

topic:

Given a sorted array and a target, find the object in the array, and returns its index. If the target is not present in the array, it will be returned in sequence inserted position.

You may assume that no duplicate elements 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

 

 

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

Implementation: The main use is half way to find, view the inserted position, when the array is no target data, left points is ta should be inserted location

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/search-insert-position
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/panjingshuang/p/11620634.html