lintcode Binary Search

来源:互联网 发布:淘宝修真记无弹窗 编辑:程序博客网 时间:2024/05/06 14:43

For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.

If the target number does not exist in the array, return -1.

Have you met this question in a real interview? 
Yes
Example

If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.

二分查找

class Solution {public:    /**     * @param nums: The integer array.     * @param target: Target number to find.     * @return: The first position of target. Position starts from 0.      */    int binarySearch(vector<int> &array, int target) {        // write your code here        int len = array.size();        int i =  recurse(array,target,0,len);        if (i != -1) {            while (array[i-1] == target) {                --i;            }            return i;        }        return -1;    }    int recurse(vector<int> &array, int target,int lo,int hi) {        if (lo == hi) {            return -1;        }        int mid = (lo + hi)>>1;        if (target > array[mid]) {            return recurse(array,target,mid+1,hi);        } else if (target < array[mid]) {            return recurse(array,target,lo,mid);        } else {            return mid;        }    }};


0 0
原创粉丝点击