现在的位置: 首页 > 综合 > 正文

Binary Search

2018年05月13日 ⁄ 综合 ⁄ 共 684字 ⁄ 字号 评论关闭

Binary search is a famous question in algorithm.

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.

样例

If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.

挑战

If the count of numbers is bigger than MAXINT, can your code work properly?

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 l = 0;
		int h = nums.length - 1;

		while (l <= h) {
			int m = l / 2 + h / 2 + (l % 2 & h % 2);
			if (nums[m] == target) {
				while (m > 0 && nums[m - 1] == target)
					m--;
				return m;
			} else if (nums[m] > target) {
				h = m - 1;
			} else if (nums[m] < target) {
				l = m + 1;
			}
		}
		return -1;
	}
}
【上篇】
【下篇】

抱歉!评论已关闭.