Lintcode二分搜索
来源:互联网 发布:大数据的盈利模式 编辑:程序博客网 时间:2024/05/01 03:57
Problem Statement
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
.
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}232, can your code work properly?
使用二分搜索时应满足:数组必须已经排序,时间复杂度是O(logn)
/*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.ExampleIf the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.ChallengeIf the count of numbers is bigger than 2^{32}232, can your code work properly? */public class Main {public static void main(String[] args) {int[] a = new int[] { 1, 2, 3, 3, 4, 5, 10 };System.out.println(binarySearch(a, 3));}private static int binarySearch(int[] arr, int target) {int left = 0;int right = arr.length - 1;int mid = (left + right) / 2;while (left < right) {if (arr[mid] > target) {right = mid;} else if (arr[mid] < target) {left = mid;} else {return mid;}mid = (left + right) / 2;}return -1;}}
0 0
- Lintcode二分搜索
- 二分查找-lintcode
- 二分查找-lintcode
- lintcode ----二分查找
- LintCode之二分查找
- lintcode:二分查找
- LintCode(easy)二分查找
- LintCode 14 二分查找
- LintCode : 二分查找
- LintCode-二分查找
- LintCode 二分查找
- lintcode:二分查找
- LintCode 二分查找
- lintcode 14. 二分查找
- Lintcode:二分查找
- Lintcode 14. 二分查找
- LintCode-搜索区间
- lintcode-搜索区间-61
- 快速打开cmd的几种方式
- [Java视频笔记]day22
- bsxfun 的理解
- 解决远程登陆误按ctrl+s锁屏假死恢复
- 证监会叫停跨界虚拟产业定增,资本市场的“+互联网”之路不好走了啊
- Lintcode二分搜索
- db2查询行数的限制
- iOS导航栏自动隐藏和显示属性,UINavigationController属性
- DiskLruCache 源码解析
- 博客搬家啦
- 关于favicon.ico
- 真机调试错误总结---does not match your bundle identifier
- 解决Xshell中文乱码问题
- 分类算法中的ROC与PR指标