How to understand "we have a mature time complexity is O (n) algorithm of any array k-th largest number of"

In the second edition wins the offer: problem solution "interview questions 39 times more than half of the number that appears array", there are so many words:
"We have time to mature complexity of any of the first to get the array is O (n) algorithm k large numbers, "
I think this sentence is something wrong, at least let me have been misunderstood.

go code is as follows:

func partition(nums []int, l, r int) int {
    // 1. 哨兵 取第一个元素
    v := nums[l]
    // 2. 大小分区的定义和初始化 [l+1,p]<v && [p+1,cur-1]>v 
    p := l
    // 3. 处理哨兵之后的每一个元素
    cur := l + 1
    for ; cur <= r; cur++ {
        if nums[cur] < v {
            nums[cur], nums[p+1] = nums[p+1], nums[cur]
            p++
        }
    }
    nums[p], nums[l] = nums[l], nums[p] // 哨兵和小分区的最后一个元素交换,使得哨兵左边是小的,右边是大的.
    return p
}

Partion time code complexity is O (n), because of the need to divide each number of small to large partitions or partitions for loop.

However, each partition where we can get the sort of location number, we can not specify. So, we need to partition multiple operating until we choose sentinels happens to be the first k large numbers, so that we can get to the "k-large" number. The worst case, we may need to call the n-th partition, then the worst time complexity is n * O (n), rather than O (n).

Prove safety offer the express misunderstood as easy for us: just call the 一次partition will be able to find a large number of k, this should be a probability event, the probability is 1 / n (only if the k-th largest number happens to be elected only satisfied when the sentry, and large numbers of k probability was chosen for the Sentinel 1 / n). The reality is, I need to call the 多次partition in order to find the k-th largest number.

In addition, the following questions relate to the use of these algorithms partition function, their common feature is the need to find digital xxx location with partition.

  1. Majority Element (blog title of this discussion): m Partition Number Find position (median: index n / 2)
  2. Kth Largest Element in an Array: partiton find the location of the number k
  3. 40 wins the offer is inscribed: minimum number of k: k partiton find the number of positions, but only return the position to the left of the number k, the number of which is smaller than those of sentinel

Welcome to the discussion, not the language, I turn engaged in .Net, research and development of Java, python, Go language, hehe.

Although I brush facing interview questions, but I do several times was deeply impressed by the wisdom algorithm inventor, really Niubi. . .

Guess you like

Origin www.cnblogs.com/yudidi/p/12148678.html