First Position of Target

    If the target number does not exist in the array, return -1.

    Example

    Challenge

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

    1. 首先对输入做异常处理,数组为空或者长度为0。
    2. 使用迭代而不是递归进行二分查找,因为工程中递归写法存在潜在溢出的可能。
    3. while终止条件应为start + 1 < end而不是start <= end,时可能出现死循环。即循环终止条件是相邻或相交元素时退出。由于这里初始化时start < end,所以一定是start + 1 == end时退出循环。
    4. 迭代终止时有两种情况,一种是在原数组中找到了,这种情况下一定是end, 因为start的更新只在nums[mid] < target.
    5. 最后判断end和的关系,先排除end为数组长度这种会引起越界的情况,然后再判断和目标值是否相等。

    时间复杂度 O(\log n), 空间复杂度 (1).
    对于题中的 follow up, Java 中数组不允许使用 long 型,如果使用 long 型,那么数组大小可大 17GB 之巨!!几乎没法用。

    • 《挑战程序设计竞赛》3.1节