239. 滑动窗口最大值
func maxSlidingWindow(nums []int, k int) []int {
que := &Queue{}
result := []int{}
for i := 0; i < k && i < len(nums); i++ {
que.push(nums[i])
}
result = append(result, que.front())
for i := k; i < len(nums); i++ {
v := nums[i - k]
que.pop(v)
que.push(nums[i])
result = append(result, que.front())
}
return result
}
type Queue struct {
data []int
length int
}
func (q *Queue) push(v int) {
for !q.empty() && v > q.back() {
q.pop_back()
}
q.push_back(v)
}
func (q *Queue) push_back(v int) {
q.data = append(q.data, v)
q.length++
}
func (q *Queue) back() (v int) {
return q.data[q.length - 1]
}
func (q *Queue) pop(v int) {
if v == q.front() {
q.pop_front()
}
}
func (q *Queue) front() (v int) {
return q.data[0]
}
func (q *Queue) pop_front() {
q.data = q.data[1:]
q.length--
}
func (q *Queue) pop_back() {
q.data = q.data[:q.length - 1]
q.length--
}
func (q *Queue) empty() bool {
return q.length <= 0
}
8.前 K 个⾼频元素