LintCode-二分查找
2017-04-17 21:10
477 查看
给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1。
样例
在数组 [1, 2, 3, 3, 4, 5, 10] 中二分查找3,返回2。
挑战
如果数组中的整数个数超过了2^32,你的算法是否会出错?
解析:
基本的数字二分法查找
样例
在数组 [1, 2, 3, 3, 4, 5, 10] 中二分查找3,返回2。
挑战
如果数组中的整数个数超过了2^32,你的算法是否会出错?
/** * 传统数组二分法查询 * @param A:需要查询的源数组 * @param target:需要查询的内容 * */ public int findPosition(int []A,int target){ if(A == null || A.length == 0){ return -1; } int start = 0; int end = A.length-1; while(start +1 <end){ int mid = start + (end - start)/2; if( target == A[mid]){ return mid; } else if(A[mid] < target){ start = mid; } else { end = mid; } } if(A[start] == target){ return start; } if(A[end] == target){ return end; } return -1; }
解析:
基本的数字二分法查找
相关文章推荐
- 一起lintcode ------- 二分查找看这篇就够了
- LintCode Binary Search 二分查找
- lintcode- 题106 排序链表转换为二分查找树
- lintcode-排序列表转换为二分查找树-106
- lintcode 容易题:Binary Search 二分查找
- LintCode : 二分查找
- LintCode-排序列表转换为二分查找树
- lintcode:二分查找
- LintCode-排序列表转换为二分查找树分析及实例
- LintCode: 二分查找
- LINTCODE---排序列表转换为二分查找树
- LintCode python 小白-简单题-457经典二分查找问题
- LintCode 二分查找
- lintCode_二分查找
- lintcode:二分查找
- Lintcode 14. 二分查找
- LintCode-查找斐波纳契数列中第 N 个数
- Codeforces Round #202 (Div. 1) A. Mafia二分查找,玩游戏
- Lintcode:字符串查找
- Codeforces #352 Div2 D Robin Hood(二分查找)