add new solutions
This commit is contained in:
parent
475d438db4
commit
1433bf4850
17 changed files with 394 additions and 0 deletions
37
solutions/2/q215/solution.go
Normal file
37
solutions/2/q215/solution.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
package q215
|
||||
|
||||
func findKthLargest(nums []int, k int) int {
|
||||
// build max-heap
|
||||
for i := 1; i < len(nums); i++ {
|
||||
for j := i; j > 0; j = (j - 1) / 2 {
|
||||
parent := (j - 1) / 2
|
||||
if nums[j] > nums[parent] {
|
||||
nums[j], nums[parent] = nums[parent], nums[j]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for range k - 1 {
|
||||
// pop the heap
|
||||
nums[0] = nums[len(nums)-1]
|
||||
nums = nums[:len(nums)-1]
|
||||
|
||||
i := 0
|
||||
for i*2+1 < len(nums) {
|
||||
l, r := i*2+1, i*2+2
|
||||
next := l
|
||||
if r < len(nums) && nums[r] > nums[l] {
|
||||
next = r
|
||||
}
|
||||
if nums[i] >= nums[next] {
|
||||
break
|
||||
}
|
||||
nums[i], nums[next] = nums[next], nums[i]
|
||||
i = next
|
||||
}
|
||||
}
|
||||
|
||||
return nums[0]
|
||||
}
|
||||
|
||||
var _ = findKthLargest
|
||||
Loading…
Add table
Add a link
Reference in a new issue