LintCode-二分查找

来源:互联网 发布:cad加密软件 编辑:程序博客网 时间:2024/04/27 23:05

给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1。

样例
在数组 [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;    }

解析:
  基本的数字二分法查找

0 0
原创粉丝点击