【问题标题】:Going through on a unsorted array, distance between elements遍历未排序的数组,元素之间的距离
【发布时间】:2012-09-29 07:23:34
【问题描述】:

建议?

给定一个未排序的数组和元素的数量,对于每个元素,如果没有数字 -1,我必须打印其自身与数组中小于他的最远元素之间的元素数量

例子:

输入: 10 6 10 3 9 15 输出: 3 1 1 -1 -1 -1

我已经做到了,但我的教授告诉它可以做得更高效,当然我实际上在做 o(n^2)。分而治之?,二分查找?

我的解决方案:

public void MedidaMolestia(int A[], int  N)
    {
    int i=0,  temp=0, k=N-1, j=0;

    for(i=0; i<N; i++) 
    {
        temp = A[i];

        for(j=N-1;j>i ; j--)
        {
            if(A[j]<temp)
            break;
        }

        if(i==j)
            System.out.print(-1 + " ");

        else 
            System.out.print((j-i)-1 + " ");
    }
}

【问题讨论】:

  • 输出不应该是3 1 2 -1 -1吗?
  • 抱歉,我无法完全理解您的问题,如果正确理解您的问题,您的代码和示例输出似乎会做不同的事情。请用清晰的例子解释

标签: arrays quicksort binary-search mergesort divide-and-conquer


【解决方案1】:

即兴发挥,我可以建议使用一点动态规划进行一些渐近改进:-

  1. 使用快速排序来获取排序后的数组中每个元素的索引。花费 O(n log n)。对于您的示例,它应该是:-

    sindex = [3 1 3 0 5 2] ( since sorted array is 3 6 9 10 10 15)
    
  2. 您需要填充一个数组 B,以便 B[i] 存储小于 i 的索引的最右边的第一个出现。执行以下操作:-

    Initialize B to [N, N,...]
    filledpos = N;
    for j = N-1 to 0 inclusive
        if(sindex[j] < filledpos) do 
        for i = sindex[j] to filledpos - 1 inclusive 
        // like if you find the 3rd smallest element fill B[4],.. B[filledpos]
           B[i] = j
        filledpos = sindex[j]
    

    对于您的示例 B = [2 2 3 3 5 5]。需要 O(n) 最坏情况

  3. 现在你知道了最右边元素

    for i = 0 to N-1
       print i - B[sindex[i]]
    

【讨论】:

    猜你喜欢
    • 2011-07-28
    • 2022-06-17
    • 2011-02-03
    • 2018-09-21
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2021-11-09
    • 2017-08-01
    相关资源
    最近更新 更多