[LintCode] First Position of Target

java 5 2016-02-29 13:03
女装

Problem

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.

Example

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

challenge

If the count of numbers is bigger than 2^32, can your code work properly?

Note

while (start + 1 < end)

+1 guaranteed that there always exists mid.
In the for loop, the else branch is actually when num[mid] >= target, why? Because this ensures that the mid pointer goes to the former ones if target is right in the middle.

Solution

class Solution {
    public int binarySearch(int[] nums, int target) {
        //write your code here
        if (nums == null || nums.length < 1) {
            return -1;
        }
        int len = nums.length;
        int start = 0, end = len - 1;
        while (start + 1 < end) {
            //for the challenge: avoid overflow
            int mid = start + (end -  start) / 2;
            if (nums[mid] < target) {
                start = mid;
            }
            else {
                end = mid;
            }
        }
        //after the while loop, only num[start] and num[end] left.
        //so just discuss them
        if (nums[start] == target) {
            return start;
        }
        if (nums[end] == target) {
            return end;
        }
        return -1;
    }
}
女装
文章评论