zoukankan      html  css  js  c++  java
  • *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
    Which company asked you this question? Airbnb Alibaba Amazon Apple Baidu Bloomberg Cisco Dropbox Ebay Facebook Google Hulu Intel Linkedin Microsoft NetEase Nvidia Oracle Pinterest Snapchat Tencent Twitter Uber Xiaomi Yahoo Yelp Zenefits
    Thanks for your feedback.
    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?

     1     public int binarySearch(int[] nums, int target) 
     2     {
     3         //write your code here
     4         if(nums.length==0)return -1;
     5         int left = 0;
     6         int right = nums.length-1;
     7         while(left+1 <right)
     8         {
     9             int mid = (left + right) /2;
    10             if(target==nums[mid])
    11             {
    12                 right = mid;
    13             }
    14             
    15             if(target<nums[mid])
    16             {
    17                 right = mid-1;
    18             }
    19             if(target>nums[mid])
    20             {
    21                 left = mid+1;
    22             }
    23             
    24         }
    25         
    26         if(nums[left]==target) return left;
    27         if(nums[right]==target) return right;
    28         return -1;
    29     }
  • 相关阅读:
    微博回调接口
    vue获取微博授权URL
    生成微博授权URL接口
    微博账号注册
    微博三方登录原理讲解
    使用celery异步发送短信
    celery配置与基本使用
    友情链接
    Linux无线网络设置--wpa_supplicant的使用
    wpa_supplicant介绍与使用
  • 原文地址:https://www.cnblogs.com/hygeia/p/4779857.html
Copyright © 2011-2022 走看看