【Leetcode】Search Insert Position

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.

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

分析:排好序的数组,可以直接用二分查找进行查询,如果找到了该值,直接返回;如果没找到,如果right已经小于0,则返回0;如果left已经大于n,则返回n,否则返回left即可。

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        if(n == 0) return 0;
        
        int left = 0;
        int right = n - 1;
        int middle = (left + right) / 2;
        
        while(left <= right)
        {
            if(A[middle] == target)
                return middle;
            
            if(A[middle] > target)
                right = middle - 1;
            else
                left = middle + 1;
                
            middle = (left + right) / 2;
        }
        
        if(right < 0) return 0;
        if(left >= n) return n;
        if(left > right) return left;
    }
};



你可能感兴趣的:(【Leetcode】Search Insert Position)