Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组中第K个最大元素 #6

Open
wisecsj opened this issue Dec 31, 2018 · 1 comment
Open

数组中第K个最大元素 #6

wisecsj opened this issue Dec 31, 2018 · 1 comment

Comments

@wisecsj
Copy link
Owner

wisecsj commented Dec 31, 2018

https://leetcode-cn.com/problemset/all/?topicSlugs=heap

func findKthLargest(nums []int, k int) int {
    createHeap(nums[:k],k)
    for i:=k;i<len(nums);i++ {
        if nums[i]>nums[0] {
            insert(nums,nums[i],k)
        }
    }
    return nums[0]
    
}
func insert(nums []int,num int,k int) {
    nums[0] = num
    var child int
    for i:=0;2*i+1<k;i=child {
        child = 2*i+1
        if child+1<k && nums[child+1] <nums[child] {
            child++
        }
        if nums[i] >nums[child] {
            nums[i],nums[child] = nums[child],nums[i]
        }else {
            break
        }
    }
}
func createHeap(nums []int,k int) {
    var minChild int
    for i:=(k-2)/2;i>=0;i-- {
        for j:=i;2*j+1<k;j=minChild {
            minChild = 2*j+1
            if minChild+1<k && nums[minChild+1]<nums[minChild] {
                minChild++
            }
            if nums[j] > nums[minChild] {
                nums[j],nums[minChild] = nums[minChild],nums[j]
                
            } else {
                break
            }
        }
    }
}
@wisecsj
Copy link
Owner Author

wisecsj commented Dec 31, 2018

1.先建立一个size为k的最小堆,时间复杂度O(k)
2.然后从从下标为k开始,遍历nums中的元素,与堆顶进行比较,然后调整堆。时间复杂度 O((n-k)logk)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant