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

首頁 > 學院 > 開發(fā)設計 > 正文

480. Sliding Window Median

2019-11-08 02:55:40
字體:
供稿:網(wǎng)友

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

Examples:

[2,3,4] , the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

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. Your job is to output the median array for each window in the original array.

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

Window position                Median---------------               -----[1  3  -1] -3  5  3  6  7       1 1 [3  -1  -3] 5  3  6  7       -1 1  3 [-1  -3  5] 3  6  7       -1 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]      6

Therefore, return the median sliding window as [1,-1,-1,3,5,6].

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

Subscribe to see which companies asked this question.

給出一個序列nums和一個窗口值k,每k個數(shù)求其中的中位數(shù)。前天剛做了類似的題(295題),求一個動態(tài)增加元素的序列的中位數(shù),這里能用295題的想法,然后還要添加刪除元素的功能。

代碼:

class Solution{public:	vector<double> medianSlidingWindow(vector<int>& nums, int k)	{		int i;		vector<double> res;		for(i = 0; i < k; ++i)		{			addNum(nums[i]);		}		for(i; i < nums.size(); ++i)		{			res.push_back(findMedian());			delNum(nums[i-k]);			addNum(nums[i]);		}		res.push_back(findMedian());		return res;	}	void addNum(int num)	{		double n = double(num);		if(set1.empty()) set1.insert(n);		else if(set1.size() > set2.size())		{			if(n >= *set1.rbegin())			{				set2.insert(n);			}			else			{				set2.insert(*set1.rbegin());				set1.erase(PRev(set1.end()));				set1.insert(n);			}		}		else		{			if(n <= *set2.begin())			{				set1.insert(n);			}			else			{				set1.insert(*set2.begin());				set2.erase(set2.begin());				set2.insert(n);			}		}	}	void delNum(int num)	{		double n = double(num);		auto iter1 = set1.find(n), iter2 = set2.find(n);		if(iter1 != set1.end())		{			set1.erase(iter1);			if(set1.size() < set2.size())			{				set1.insert(*set2.begin());				set2.erase(set2.begin());			}		}		else		{			set2.erase(iter2);			if(set1.size() > set2.size() + 1)			{				set2.insert(*set1.rbegin());				set1.erase(prev(set1.end()));			}		}	}	double findMedian()	{		if(set1.size() > set2.size())		{			return *set1.rbegin();		}		else		{			return (*set1.rbegin() + *set2.begin()) / 2;		}	}private:	multiset<double> set1, set2;};


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 蓝田县| 临武县| 惠东县| 嘉祥县| 石泉县| 大悟县| 凤阳县| 武定县| 绥滨县| 东海县| 西盟| 张家口市| 大埔县| 遂昌县| 汉沽区| 顺义区| 无极县| 临武县| 黎城县| 墨玉县| 深圳市| 乌鲁木齐市| 公安县| 霞浦县| 黔西| 乌审旗| 鄄城县| 康保县| 高州市| 集贤县| 苗栗市| 安平县| 庆元县| 迁西县| 资源县| 曲周县| 慈溪市| 石台县| 潮安县| 昌平区| 临西县|