Lintcode:二分查找

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


在数组 [1, 2, 3, 3, 4, 5, 10] 中二分查找3,返回2



python:

class Solution:
    # @param nums: The integer array
    # @param target: Target number to find
    # @return the first position of target in nums, position start from 0
    def binarySearch(self, nums, target):
        # write your code here
        low = 0
        high = len(nums) - 1
        while low <= high:
            middle = (high + low) // 2
            if nums[middle] < target:
                low = middle + 1
            elif nums[middle] > target:
                high = middle - 1
            else:
                while nums[middle] == nums[middle - 1]:
                    middle -= 1
                return middle
        return -1


C++:

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
        if (array.size() == 1)
        {
            if (array[0] == target)
                return 0;
        }
        int start = 0;
        int end = array.size();
        int middle = end / 2;
        while (array[middle] != target)
        {
            if (array[middle] > target)
            {
                end = middle - 1;
            }
            else
            {
                start = middle + 1;
            }
            middle = (start + end) / 2;
            if (array[middle] < target && array[middle + 1] > target)
                return -1;
        }
        while (array[middle] == array[middle - 1])
        {
            middle--;
        }
        return middle;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值