在0-1阵列中找到1的数字,并且所有1都在“左侧”?

时间:2013-03-12 21:03:35

标签: algorithm math binary-search

数组由N个1和0组成,所有1都在0之前。在数组中找不到1的内容。很明显,使用二进制搜索它是O(log N)。是否有算法在O(log(1' s))时间内执行此操作?

3 个答案:

答案 0 :(得分:7)

您实际上可以在O(lg m)时间内执行此操作,其中m是1的数量。我不会给出整个算法,因为这看起来像是作业,但这里有一个提示:尝试“反转”二进制搜索,以便扩展搜索区域而不是收缩它。

答案 1 :(得分:1)

如果你只是迭代这个数组,你计算所有的1,最后找到0你做了N + 1步,所以我认为这是O(n + 1)算法。

答案 2 :(得分:0)

class OneZero
{

    public static int binary_search (byte[] array, int start, int end, int value)
    {

        if (end <= start) return -1;

        if (Math.floor((start+end)/2) == value) return Math.floor((start+end)/2);

        return binary_search (array, start, Math.floor((start+end)/2)-1, value);

    }

    public static int nbOfOnes (byte[] array, int value)
    {

        return (binary_search(array, 0, array.length,value)+1);

    }

    public static void main ()
    {

        byte[] arr = { 1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0 };

        System.out.println(" number of 1s is: "+nbOfOnes(arr,1));

    }

}
相关问题