首页 > 其他 > 详细

*Binary Search

时间:2015-09-03 06:58:19      阅读:231      评论:0      收藏:0      [点我收藏+]

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     }

 

*Binary Search

原文:http://www.cnblogs.com/hygeia/p/4779857.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!