国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

239. Sliding Window Maximum

2019-11-08 02:29:31
字體:
來源:轉載
供稿:網友

Given an array 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 thek numbers in the window. Each time the sliding window moves right by one position.

For example,Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position                Max---------------               -----[1  3  -1] -3  5  3  6  7       3 1 [3  -1  -3] 5  3  6  7       3 1  3 [-1  -3  5] 3  6  7       5 1  3  -1 [-3  5  3] 6  7       5 1  3  -1  -3 [5  3  6] 7       6 1  3  -1  -3  5 [3  6  7]      7

Therefore, return the max sliding window as [3,3,5,5,6,7].

Note: You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

Follow up:Could you solve it in linear time?

Hint:

How about using a data structure such as deque (double-ended queue)?The queue size need not be the same as the window’s size.Remove redundant elements and the queue should store only elements that need to be considered.

Subscribe to see which companies asked this question.

給出一個序列nums和一個窗口值k,每k個數求其中的最大值。要求線性時間復雜度。用deque來實現,用deque保存索引值,比較前面的索引值放在deque的后面,對于當前的數,與deque中的數比較。deque中比當前數還小的在當前以及以后的窗口中都不可能是最大值,所以可以pop出去。直到當前數比deque頭部的值小,然后把當前數push進去。這樣deque就是數值從小到大排序,索引從大到小排序的。為了保持子序列不超過窗口大小,如果deque的尾部索引值比下一個窗口的最左端索引要小的話,就pop出去。每個窗口的最大值就是當前deque的尾部索引值對應的序列中的值。

代碼:

class Solution{public:	vector<int> maxSlidingWindow(vector<int>& nums, int k) 	{		deque<int> window;		vector<int> res;		for(int i = 0; i < nums.size(); ++i)		{			while(!window.empty() && nums[window.front()] <= nums[i]) window.pop_front();			window.push_front(i);			if(i >= k-1) res.push_back(nums[window.back()]);			if(window.back() <= i-k+1) window.pop_back();		}		return res;	}};


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 芒康县| 岑巩县| 洮南市| 望城县| 桑日县| 永胜县| 修文县| 松阳县| 称多县| 灵璧县| 云浮市| 姜堰市| 全州县| 文昌市| 新乡市| 肥西县| 三原县| 宜川县| 牡丹江市| 马尔康县| 邳州市| 江达县| 武川县| 三门峡市| 西乌| 长子县| 新邵县| 堆龙德庆县| 巴楚县| 平乡县| 苏尼特左旗| 蒲江县| 永城市| 罗山县| 连云港市| 高雄市| 富宁县| 竹溪县| 大同县| 游戏| 棋牌|