简体   繁体   English

Kth最大元素

[英]Kth Largest Element

I am trying to solve the Kth Largest Element problem.I don't why following bugs appeared. 我正在尝试解决第K个最大元素问题。我不为什么会出现以下错误。 "E: 6,16: Undefined variable 'quickSelect' (undefined-variable) E: 27,19: Undefined variable 'quickSelect' (undefined-variable) E: 30,19: Undefined variable 'quickSelect' (undefined-variable)" Here are my codes. “ E:6,16:未定义变量'quickSelect'(未定义变量)E:27,19:未定义变量'quickSelect'(未定义变量)E:30,19:未定义变量'quickSelect'(未定义变量)”这是我的代码。

def kthLargestElement(self, k, A):
     return quickSelect(A, 0, len(A) - 1, k)

def quickSelect(self, nums, start, end, k):
    if start == end:
        return nums[start]

    i = start
    j = end
    pivot = (nums[start] + nums[end]) // 2

    while i <= j:
        while i <= j and nums[i] < pivot:
            i += 1
        while i <= j and nums[j] > pivot:
            j -= 1
        if i <=j:
            nums[i], nums[j] = nums[j], nums[i]
            i += 1
            j -= 1

    if start + k - 1 <= j:
        return quickSelect(nums, start, j, k)

    if start + k - 1 >= i:
        return quickSelect(nums, i, end, k - (i - start))

    return nums[j + 1]

Python cannot find quickSelect because it's looking for it in the global namespace rather than looking inside your class. Python无法找到quickSelect因为它正在全局名称空间中寻找它,而不是在类内部寻找它。 To fix this you can invoke your function using self.quickSelect(...) instead of quickSelect(...) . 为了解决这个问题,你可以通过调用你的函数self.quickSelect(...)而不是quickSelect(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM