*Binary Search

來源:互聯網
上載者:User

標籤:

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?

YesWhich 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     }

 

*Binary Search

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.