二分查找-lintcode
来源:互联网 发布:软件测试 编辑:程序博客网 时间:2024/04/29 00:57
给定一个排序的整数数组(升序)和一个要查找的整数target
,用O(logn)
的时间查找到target第一次出现的下标(从0开始),
如果target不存在于数组中,返回-1
。
在数组 [1, 2, 3, 3, 4, 5, 10]
中二分查找3
,返回2
。
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 int left = 0; int right = array.size()-1; while(left<=right){ int mid = (right+left)/2; if(target<array[mid]) right = mid-1; else if (target>array[mid]) left = mid +1; else{ //处理出现有多个target的情况。 int j = mid; for(;j>=0&&array[j]==target;j--) ; return j+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之经典二分查找
- DES、3DES
- Android SDK Manager无法更新的解决方案
- [网络编程]——UDP
- Volley的使用
- android学习——Handler引起的内存泄露及解决方法
- 二分查找-lintcode
- iOS开发总结之项目开发中使用UITableView自定义多级表格&自定义cell
- You have an error in your SQL syntax;
- Linux epoll详解
- Python语言进行机器学习的开源项目
- LeetCode 276. Paint Fence(篱笆涂色)
- Android 图片如何高效加载与缓存 (5) —— RecyclerView与自定义线程池结合 优化加载
- linux下Epoll实现简单的C/S通信
- 大部分人都会做错的经典JS闭包面试题