国产探花免费观看_亚洲丰满少妇自慰呻吟_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;	}};


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 秦皇岛市| 东乌| 福贡县| 突泉县| 图们市| 峨眉山市| 吴堡县| 邵武市| 新营市| 萨嘎县| 南充市| 青海省| 宿松县| 麻江县| 红桥区| 英吉沙县| 页游| 秦安县| 扎囊县| 乐山市| 天等县| 象山县| 临江市| 邢台市| 汉寿县| 逊克县| 巫溪县| 洪洞县| 郸城县| 黄龙县| 横峰县| 巫溪县| 甘德县| 兰坪| 喀喇沁旗| 牙克石市| 龙门县| 泊头市| 周至县| 唐海县| 信阳市|