LintCode Binary Search
2015-09-12 23:01
232 查看
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; } };
相关文章推荐
- MySQL BLOB 类型介绍
- Jmeter实现webservice协议的脚本
- curl 使用详解
- 第二周
- HDU 1710 Binary Tree Traversals
- HDU 5012 Dice (2014年西安赛区网络赛F题)
- BZOJ 2599: [IOI2011]Race( 点分治 )
- Fragment学习笔记
- CQL IN 语法的应用方法
- Unity3D笔记第六天——脚本常用核心类
- 随记一(独夜,十年)
- 【学习日记】集合框架知识点总结(1)--Collection
- 网络请求配置
- Hbase写数据,存数据,读数据的详细过程
- struts2(1)
- Git添加空文件夹的方法
- MysqL Blob 实例代码
- 解决Error:No suitable device found: no device found for connection "Syst
- MyEclipse中的快捷键组合
- 关于设置applicationIconBadgeNumber提醒数字的问题