14. 二分查找

Description

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.

Example

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

Challenge
If the count of numbers is bigger than 2^32, can your code work properly?

        int low = 0;
        int high = nums.length-1;
        int pos = -1;
        while(low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] == target) {
                pos =  mid;
            } 
            // TODO:必须是>=
            if(nums[mid] >= target) {
                high = mid - 1;
            }
            if(nums[mid] < target) {
                low = mid + 1;
            }
        }
        return pos;

描述
给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1。

您在真实的面试中是否遇到过这个题?  
样例
在数组 [1, 2, 3, 3, 4, 5, 10] 中二分查找3,返回2。

挑战
如果数组中的整数个数超过了2^32,你的算法是否会出错?

posted @ 2019-04-02 21:40  故人叹  阅读(90)  评论(0)    收藏  举报