Re: [闲聊] 每日leetcode

楼主: JIWP (JIWP)   2024-11-28 21:13:56
3346. Maximum Frequency of an Element After Performing Operations I
3347. Maximum Frequency of an Element After Performing Operations II
两题差不多,放在一起讲
思路:
先记录nums中每个数字出现的次数
找出nums矩阵里的最大值maxnum
接着从0~maxnum每个数都去找距离这个数[-k,k]以内的值在nums出现的次数
基本上类似prefixsum
从0 -> maxnum跑一次、maxnum -> 0再跑一次
最后找出0~maxnum中是哪个值在[-k,k]这个范围内在nums出现最多次
就是答案了
golang code :
func maxFrequency(nums []int, k int, numOperations int) int {
max_num := slices.Max(nums)
count, adjacent := make([]int, max_num+1), make([]int, max_num+1)
for _, val := range nums {
count[val]++
}
adj := 0
for i := 0; i <= max_num; i++ {
if i-k-1 > -1 {
adj -= count[i-k-1]
}
adjacent[i] = adj
adj += count[i]
}
ans, adj := 0, 0
for i := max_num; i > -1; i

Links booklink

Contact Us: admin [ a t ] ucptt.com