代码随想录算法训练营第十四天 | 239. 滑动窗口最大值 347.前 K 个高频元素 总结

239. 滑动窗口最大值 

You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

#1 自己看到题目的第一想法     

sliding window,也是双指针的一种。

先用for循环,循环nums中的每一个元素。

如果i - temp[0] === k,那么要删去temp[0]因为他超出范围了。

然后比较temp中的每一个元素的值和nums[i],仅保留大于nums[i]的元素在temp中 (注意需要从后向前比,用while)。

temp.push(nums[i])。

将temp[0]push到result中去。

#2 看完代码随想录之后的想法   

由于栈结构的特殊性,非常适合做对称匹配类的题目。

栈用来做匹配类型的题很常见。类似的,本题是queue的应用,queue通常用于做sliding window和for 循环连用。本题所需要的就是一个单调递增的队列。

此外,使用单调队列的时间复杂度是 O(n)。尽管还有pop操作,但是需要注意的是nums中的每个元素最多也就是被 push_back 和 pop_back 各一次,没有任何多余操作,所以整体的复杂度还是 O(n)。

347.前 K 个高频元素 

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

#1 自己看到题目的第一想法 

第一想法是hash map,统计每个数字出现的frequency,再找到k most frequent elements。时间复杂度是 m*k。

没有想到这个和queue有什么关系.....

#2 看完代码随想录之后的想法    

[1,1,1,2,2,3] 

js中的priority queue可以通过const heap = new MinPriorityQueue()来实现。

#3 收获

let sortedArray = [...map.entries()].sort((a, b) => b[1] - a[1]);

let sortedArray = Object.entries(map).sort((a, b) => b[1] - a[1]);

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容