LintCode Binary Search 二分查找

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.

class Solution {
/**
* @param nums: The integer array.
* @param target: Target to find.
* @return: The first position of target. Position starts from 0.
*/
public int binarySearch(int[] nums, int target) {
int low = 0;
int high = nums.length;
while(low <= high) {
int mid = (high - low)/2 + low;
if(nums[mid] == target){
while(mid - 1 >= 0 && nums[mid - 1] == target){
mid--;
}
return mid;
}
else if(nums[mid] < target){
low = mid + 1;
}else {
high = mid - 1;
}
}
return -1;
}
}

一起lintcode ------- 二分查找看这篇就够了

2017-07-17 16:20:56

二分查找(Binary Search) 常见问题解决方法总结

2013-12-13 21:48:07

STL之二分查找 (Binary search in STL)

2007-11-21 23:05:00

二分查找算法(Binary Search)的实现

2010-07-15 03:09:00

二分查找函数binary_search

2007-05-26 23:57:00

SAP ABAP二分查找（binary search）实际问题的深度分析

2016-09-05 10:17:21

二分查找排序(binary search sort)

2017-12-31 22:58:35

ABAP性能优化技巧—使用二分查找(Binary Search)选项

2016-11-02 14:52:11

实现二分查找树的迭代器（Binary Search Tree Iterator ）

2015-05-09 16:10:32

[LintCode] 将二叉查找树转换成双链表 Convert Binary Search Tree to Doubly Linked List

2016-04-25 22:26:32