二进制搜索,计算重复

时间:2013-01-07 13:53:14

标签: java

我已对数组进行了排序

{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(顶部索引 - 底部索引)将给出数组中目标编号的时间。

我的代码是否已登录? 请帮忙! :)

    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;

    }

}

1 个答案:

答案 0 :(得分:2)

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

所以我建议您只需将索引传递给findTopIndexfindBottomIndex并使用它。我可以写出整个解决方案,但是你自己来做它会更好。

相关问题