【问题标题】:Occurrence of number in array,with complexity log n algorithm and c数组中数字的出现,复杂度为log n算法和c
【发布时间】:2021-01-16 10:42:41
【问题描述】:

嗨,天才,祝你有美好的一天 情况:

T [M] 数组按升序排序。
编写一个算法,计算数组 T[M] 中整数 x 的出现次数。
x 与 T 的元素比较的次数,必须是 log n 阶

我的尝试是:

def Occurrence(T,X,n):{
   
 
       if ( n=0 ){ return 0;}
        else { 

            Occurrence(T,X,n/2);

            if( T[n]==X ){  return 1+Occurrence(T,x,n/2); }
            else { return Occurrence(T,x,n/2); }

 
 }the end of code
complexity is :
                   0 if n=0
we have      O(n)={
                   1+O(n/2) if n>0
O(n)=1+1+1+....+O(n/2^(n))=n+O(2/2^(n))
when algorithm stopp if{existe k  n=2^(k),so   O(n)=n+1 } 
n/2^(n)=1)  =>   O(n)=log(n)+1, so you think my code is true ?
</pre>

【问题讨论】:

  • 1.二进制搜索第一次出现 2. 二进制搜索最后一次出现。这有什么问题?
  • 首先谢谢你的反应。情况不是说第一次出现,我想要所有的出现,我问这些答案是对问题的回应还是存在其他解决这个问题的答案,或者我的尝试不是正确。
  • 如果数组出现 ~N 次您要搜索的数字,您的代码目前无法实现 log(N) 复杂度,因为在这种情况下您需要执行 ~N 次加法。此外,我不确定 else {return Occurence; } 是否取决于语言,这要么是不可能的,要么返回指向可能不是您想要的函数的指针。
  • 谢谢我已经编辑过其他{return Occurrence; },

标签: algorithm math complexity-theory division find-occurrences


【解决方案1】:

查看binary search variants,它给出了所需元素的最左边和最右边的索引,然后返回index_difference + 1

您可以在 C++ STL 中使用 lower_bound 和 upper_bound,在 Python 中使用 bisect_left 和 bisect_right,如果有类似的功能,或者从 Wiki 引用中实现伪代码。

【讨论】:

    【解决方案2】:

    如果数组已排序

    import bisect 
    
    T = [1, 3, 4, 4, 4, 6, 7]
    x = 4
    right = bisect.bisect(T, x)
    if(right == 0 or T[right - 1] != x):
        print("Count:0")
    else:
        left = bisect.bisect_left(T, x)
        print("Count:", right - left)
    

    2Log(n)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-22
      • 2015-06-12
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 2018-11-26
      相关资源
      最近更新 更多