u
This commit is contained in:
@@ -1,48 +1,60 @@
|
||||
package top100liked
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// https://leetcode.cn/problems/kth-largest-element-in-an-array/?envType=study-plan-v2&envId=top-100-liked
|
||||
// https://leetcode.cn/problems/largest-rectangle-in-histogram/?envType=study-plan-v2&envId=top-100-liked
|
||||
|
||||
func findKthLargest(nums []int, k int) int {
|
||||
n := len(nums)
|
||||
target := n - k // 第 k 大 = 升序第 n-k 位
|
||||
var quickSelect func(l, r int) int
|
||||
quickSelect = func(l, r int) int {
|
||||
if l == r {
|
||||
return nums[l]
|
||||
// 暴力法,超时
|
||||
// func largestRectangleArea(heights []int) int {
|
||||
// maxArea := 0
|
||||
// // i 是每个组合中的元素数量
|
||||
// for i := 1; i <= len(heights); i++ {
|
||||
// // j 是在整个 heights 中滑动的次数
|
||||
// for j := 0; j < len(heights)-i+1; j++ {
|
||||
// // 计算
|
||||
// maxArea = max(maxArea, slices.Min(heights[j:j+i])*i)
|
||||
// }
|
||||
// }
|
||||
// return maxArea
|
||||
// }
|
||||
|
||||
func largestRectangleArea(heights []int) int {
|
||||
stack := []int{}
|
||||
maxArea := 0
|
||||
for i := range len(heights) + 1 {
|
||||
if len(stack) == 0 {
|
||||
stack = append(stack, i)
|
||||
continue
|
||||
}
|
||||
pivot := nums[l+rand.Intn(r-l+1)]
|
||||
// 三路分区:[l..lt-1] < pivot, [lt..gt] == pivot, [gt+1..r] > pivot
|
||||
lt, gt, i := l, r, l
|
||||
for i <= gt {
|
||||
switch {
|
||||
case nums[i] < pivot:
|
||||
nums[lt], nums[i] = nums[i], nums[lt]
|
||||
lt++
|
||||
i++
|
||||
case nums[i] > pivot:
|
||||
nums[gt], nums[i] = nums[i], nums[gt]
|
||||
gt--
|
||||
default:
|
||||
i++
|
||||
var cur int
|
||||
if i == len(heights) {
|
||||
cur = 0
|
||||
} else {
|
||||
cur = heights[i]
|
||||
}
|
||||
if cur >= heights[stack[len(stack)-1]] {
|
||||
stack = append(stack, i)
|
||||
} else {
|
||||
for len(stack) > 0 && heights[stack[len(stack)-1]] > cur {
|
||||
top := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
width := i
|
||||
if len(stack) > 0 {
|
||||
width = i - stack[len(stack)-1] - 1
|
||||
}
|
||||
maxArea = max(maxArea, heights[top]*width)
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case target < lt:
|
||||
return quickSelect(l, lt-1)
|
||||
case target > gt:
|
||||
return quickSelect(gt+1, r)
|
||||
default:
|
||||
return pivot
|
||||
stack = append(stack, i)
|
||||
}
|
||||
}
|
||||
return quickSelect(0, n-1)
|
||||
return maxArea
|
||||
}
|
||||
|
||||
func Test(t *testing.T) {
|
||||
findKthLargest([]int{3, 2, 1, 5, 6, 4}, 2)
|
||||
fmt.Println(largestRectangleArea([]int{2, 1, 5, 6, 2, 3}))
|
||||
fmt.Println(largestRectangleArea([]int{1}))
|
||||
fmt.Println(largestRectangleArea([]int{2, 1, 2}))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user