LintCode : 二分查找
来源:互联网 发布:kindle微信推送 知乎 编辑:程序博客网 时间:2024/04/29 01:07
LintCode : 二分查找
题目
给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1。
样例
在数组 [1, 2, 3, 3, 4, 5, 10] 中二分查找3,返回2。
思路
首先二分查找到target所在的位置,再向前寻找第一个target的位置。
代码
int binarySearch(vector<int> &array, int target) { int p = 0; int r = array.size() - 1; int q = -1; while(p <= r) { q = (p + r) / 2; if(array[q] == target) { break; } else if(array[q] > target) { r = q - 1; } else { p = q + 1; } } if(array[q] == target) { while(array[q] == target) { q--; } return q + 1; } return -1;}
0 0
- 二分查找-lintcode
- 二分查找-lintcode
- lintcode ----二分查找
- LintCode之二分查找
- lintcode:二分查找
- LintCode(easy)二分查找
- LintCode 14 二分查找
- LintCode : 二分查找
- LintCode-二分查找
- LintCode 二分查找
- lintcode:二分查找
- LintCode 二分查找
- lintcode 14. 二分查找
- Lintcode:二分查找
- Lintcode 14. 二分查找
- LintCode Binary Search 二分查找
- 二分查找——LintCode
- lintcode之经典二分查找
- 浅析网络数据解析
- VMware虚拟机启动Ubuntu时提示piix4_smbus: Host SMBus controller not enabled错误的解决办法
- HDU 1166敌兵布阵
- C primer plus 第七章 C控制语句-分支和跳转 编程练习个人答案
- Java常用jar包用途
- LintCode : 二分查找
- 对replaceA11(".", "/")的理解
- JavaScript的一些基本知识 -- DOM操作
- 利用.sig文件验证数据的完整性
- Android Studio 和AsyncTask的小问题
- HDU 2303 The Embarrassed Cryptographer
- oracle用户密码密码复杂度设置
- MoodAnalyseSystem需求
- 简单粗暴的切面实战