码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode Binary Search

时间:2015-08-03 19:08:48      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:二分查找   搜索   binary search   

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;
        }
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

lintcode Binary Search

标签:二分查找   搜索   binary search   

原文地址:http://blog.csdn.net/susser43/article/details/47259983

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!