2

我已经排序了数组

{1,2,3,5,5,5,7,8,8}

我想计算仅在 longn 的数组中找到我发送的数字的次数。

例如:

public static int count(int[] array,5)

会回复 3

public static int count(int[] array,8)

会回复2

所以我的计划是:

1)进行二分查找以查找数字

2)二分查找上边框索引和下边框索引。

3) print (top index - bottom index) 会给我数组中目标数字的时间。

我的代码是 logn 吗?请帮忙!:)

    public class binarySearch
{
    public static void main(String[]args)
    {
        System.out.println("d");
        int[]data={1,1,2,3,1,1,1};
        System.out.println(count(data,1));
    }

    public static int count(int[] a, int x)
    {
        int low=0;
        int high = a.length-1;
        int count=0;

        while(low <=high)
        {
            int mid=((low+high)/2);         
            if(x>a[mid])
                low=mid+1;
            if(x<a[mid])
                high=mid-1;

            if(x==a[mid])            
            {
                int top=findTopIndex(a,x,mid);                
                int bottom=findBottomIndex(a,x,mid);
                return (top-bottom);

            }

        }    
        return 111111111;

    }

    public static int findTopIndex(int[] a, int x, int index)
    {
        int low=index;
        int high = a.length-1;    
        int mid;
        if(x==a[high])
        return high;

        while(low <= high)
        {            
           mid=((low+high)/2);         
           if(x<a[mid]&&x==a[mid-1])
           return mid-1;
           else if(x==a[mid])
                low=mid+1;
           else if(a[mid]>x && a[mid-1]!=x)
           high=mid-1;


        } 
        return 11111111;

    }
    public static int findBottomIndex(int[] a, int x, int index)
    {
        int low=0;
        int high = index-1;    
        int mid;
        if(x==a[low])
        return low-1;

        while(low <= high)
        {            
         mid=((low+high)/2);         
           if(x>a[mid]&&x==a[mid+1])
           return mid;
           else if(x==a[mid])
                high=mid-1;
           else if(a[mid]<x && a[mid+1]!=x)
           low=mid+1;

        } 
        return 111;

    }

}
4

1 回答 1

2

您所写的内容非常接近您需要的解决方案。您首先进行二进制搜索以找到您正在搜索的数字的单个实例(假设它在 position 上找到index),然后您再进行两次二进制搜索 - 一次用于序列0, index,一次用于index, size查找两者中的位置序列是找到的数字。

所以我建议你简单地将索引传递给两者findTopIndexfindBottomIndex利用它。我可以编写整个解决方案,但你自己来解决会更好。

于 2013-01-07T14:01:09.893 回答