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循環(huán)撒轮,循環(huán)nums中的每一個(gè)元素产捞。
如果i - temp[0] === k醇锚,那么要刪去temp[0]因?yàn)樗龇秶恕?/p>
然后比較temp中的每一個(gè)元素的值和nums[i],僅保留大于nums[i]的元素在temp中 (注意需要從后向前比,用while)焊唬。
temp.push(nums[i])恋昼。
將temp[0]push到result中去。
#2 看完代碼隨想錄之后的想法? ?
由于棧結(jié)構(gòu)的特殊性赶促,非常適合做對稱匹配類的題目液肌。
棧用來做匹配類型的題很常見。類似的鸥滨,本題是queue的應(yīng)用嗦哆,queue通常用于做sliding window和for 循環(huán)連用。本題所需要的就是一個(gè)單調(diào)遞增的隊(duì)列婿滓。
此外老速,使用單調(diào)隊(duì)列的時(shí)間復(fù)雜度是 O(n)。盡管還有pop操作凸主,但是需要注意的是nums中的每個(gè)元素最多也就是被 push_back 和 pop_back 各一次橘券,沒有任何多余操作,所以整體的復(fù)雜度還是 O(n)卿吐。
347.前 K 個(gè)高頻元素?
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旁舰,統(tǒng)計(jì)每個(gè)數(shù)字出現(xiàn)的frequency,再找到k?most frequent elements嗡官。時(shí)間復(fù)雜度是 m*k箭窜。
沒有想到這個(gè)和queue有什么關(guān)系.....
#2 看完代碼隨想錄之后的想法? ??
[1,1,1,2,2,3]?
js中的priority queue可以通過const heap = new MinPriorityQueue()來實(shí)現(xiàn)。
#3 收獲
let sortedArray = [...map.entries()].sort((a, b) => b[1] - a[1]);
let sortedArray = Object.entries(map).sort((a, b) => b[1] - a[1]);