滑动窗口的最大值

1.改进的暴力法。

class Solution {
public:
	//只考虑两端增删变化的影响
	int MaxinW(const vector<int>& num, int low, int high)
	{
		int MaxVal = INT_MIN;
		for (int j = low; j <= high; j++)
			MaxVal = max(num[j], MaxVal);

		return MaxVal;
	}
	vector<int> maxInWindows(const vector<int>& num, unsigned int size)
	{
		vector<int>res;
		int len=num.size();
		if (len <= 0||size<=0||size>len)return res;
		int MaxVal = MaxinW(num, 0, size - 1); res.push_back(MaxVal);
		for (int low = 1, high = size; high < len; low++,high++)
		{
			if (num[high] >= MaxVal)
				MaxVal = num[high];
			if (num[low - 1] == MaxVal)
			    MaxVal = MaxinW(num, low, high);
			res.push_back(MaxVal);
		}
		return res;
	}

};

2.双端队列

class Solution {
public:
	//双端队列
	//时间复杂度o(n),空间复杂度为o(n)
	//deque s中存储的是num的下标
	vector<int> maxInWindows(const vector<int>& num, unsigned int size)
	{
		vector<int>res;
		deque<int>s;
		int len=num.size();
		if (len <= 0||size<=0||size>len)return res;		 
		for (int i = 0;i < len; i++)
		{
			while (!s.empty() && num[s.back()] <= num[i])//当前值比队列从后往前的大,成为下一个待选值
				s.pop_back();
			while (!s.empty()&&i - s.front() + 1>size)//最大值已不在窗口中
				s.pop_front();
			s.push_back(i);
			
			if (i + 1 >= size)//当滑动窗口首地址i大于等于size时才开始写入窗口最大值
			 res.push_back(num[s.front()]);
		}
		return res;
	}

};

你可能感兴趣的:(剑指offer题,剑指offer)