*binary Search

Source: Internet
Author: User

For a given sorted array (ascending order) and a number target , find the first index of this number in time O(log n) complexit Y.

If the target number does not exist in the array, return -1 .

Has you met this question in a real interview?

YesWhich company asked do you question?AirbnbAlibabaAmazonAppleBaiduBloombergCiscoDropboxEbayFacebook 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 intBinarySearch (int[] Nums,inttarget)2     {3         //Write your code here4         if(nums.length==0)return-1;5         intleft = 0;6         intright = Nums.length-1;7        While  (left+1 < right) 8         {9             intMid = (left + right)/2; Tenif(target==nums[mid])  right = mid; -  }  -              the             if(target<Nums[mid]) -             { -right = Mid-1; -             } +             if(target>Nums[mid]) -             { +left = mid+1; A             } at              -         } -          -         if(Nums[left]==target)returnLeft ; -         if(Nums[right]==target)returnRight ; -         return-1; in}

*binary Search

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.