zoukankan      html  css  js  c++  java
  • LintCode 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.
    Challenge
    If the count of numbers is bigger than 2^32, can your code work properly?

    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
            long len = array.size();
            long lo = 0;
            long hi = len;
            while (lo < hi) {
                long mid = (lo + hi) / 2;
                if (array[mid] < target) {
                    lo = mid + 1;
                } else {
                    hi = mid;
                }
            }
            
            return (lo == len || array[lo] != target) ? -1 : lo;
        }
    };
    
    
  • 相关阅读:
    react实现拖拽
    JS实现判断滚动条滚到页面底部并执行事件的方法
    获取地址中的参数 封装在params对象里面
    git常用命令
    Linux定时任务Crontab命令详解
    tars 部署
    tars 问题汇总
    Mac
    http head
    SSL
  • 原文地址:https://www.cnblogs.com/lailailai/p/4803825.html
Copyright © 2011-2022 走看看