[35] C-brush LeetCode search insertion position (E)

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

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.

Finally use binary search. See the array is sorted, look, conditioned reflex should be half. 2 ^ 32 but also find the number 32 times, so the power of binary search is still very large.

int searchInsert(int* nums, int numsSize, int target){
    int index = -1;
    int begin = 0;
    int end = numsSize - 1;
    int mid;

    while (index == -1) {
        mid = (begin + end)/2;
        
        if (nums[mid] == target) {
            index = mid;
        } else if (target < nums[mid]) {
            if ((mid == 0) || (target > nums[mid - 1])) {
                index = mid;
            }
            end = mid  - 1;
        } else if (target > nums[mid]) {
            if ((mid == numsSize - 1) || (target < nums[mid + 1])) {
                index = mid + 1;
            }
            
            begin = mid + 1;
        }
    }
    return index;
}

 

Published 92 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/jin615567975/article/details/104306803