1 Star 0 Fork 0

catyMap/AlgorithmNote

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
KthLargest.go 1.23 KB
一键复制 编辑 原始数据 按行查看 历史
catyMap 提交于 2021-03-30 22:11 +08:00 . 未归类算法题目提交
package main
import (
"fmt"
"sort"
)
// 切片本来就是引用类型
type KthLargest struct {
k int
nums []int
}
func Constructor(k int, nums []int) KthLargest {
sort.Slice(nums, func(i, j int) bool {
return nums[i] > nums[j]
})
return KthLargest{
k: k,
nums: nums,
}
}
// 找第k大,也相当于找第len-k+1小 // TODO 也可以从构造那入手,直接改变k值即可
func (this *KthLargest) Add(val int) int {
if len(this.nums) - this.k + 1 < this.k {
return this.BigAdd(val)
}
return this.SmallAdd(val)
}
func (this *KthLargest) BigAdd(val int) int {
if len(this.nums) < this.k || val >= this.nums[this.k - 1] {
this.nums = append(this.nums , val)
sort.Slice(this.nums, func(i, j int) bool {
return this.nums[i] > this.nums[j]
})
}
return this.nums[this.k-1]
}
func (this *KthLargest) SmallAdd(val int) int {
if len(this.nums) < this.k || val >= this.nums[this.k - 1] {
this.nums = append(this.nums , val)
sort.Slice(this.nums, func(i, j int) bool {
return this.nums[i] > this.nums[j]
})
}
return this.nums[this.k-1]
}
func main() {
obj := Constructor(3,[]int{4,5,8,2})
p1 := obj.Add(3)
p2 := obj.Add(5)
p3 := obj.Add(10)
p4 := obj.Add(9)
p5 := obj.Add(4)
fmt.Println(p1,p2,p3,p4,p5)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dogemap/algorithm-note.git
git@gitee.com:dogemap/algorithm-note.git
dogemap
algorithm-note
AlgorithmNote
dc486f96f6c1

搜索帮助