剑指offer-59

队列的最大值

59.1 滑动窗口的最大值

解法一:用一个vector队列来记录最大值

每次vector传入一个值,如果该值大于队头(当前最大值),队列清空,传入值;如果该值小于对头,大于队尾,剔除队尾,直至大于当前值时,弹入该值

每次最大值即队头,注意窗口大于和等于组长度的情况

解法二:用两个栈模拟一个队列操作,用一个栈记录栈最大值,一个变量max记录总最大值。

栈A模拟进入,栈B模拟输出,栈C记录输出栈最大值情况

每次从A进入,检查栈中元素总数大小,AB模拟队列弹出,调整C

比较栈C头和max大小决定最大值

59.2 队列的最大值

一个队列装原始值,一个队列记录最大值,操作同上

解法一:
vector maxInWindows(const vector& num, unsigned int size)//diy
{
	vector retVector;
	if (num.size() <= 0 || size <= 0 || num.size() < size) return retVector;

	vector maxVector;
	if (size==1)
	{
		for (auto& it : num)
			retVector.push_back(it);
	}
	else if (num.size()==size)
	{
		int max = 0;
		for (auto& it : num)
			max = max > it ? max : it;
		retVector.push_back(max);
	}
	else
	{
		maxVector.push_back(num[0]);
		for (int i = 1; i < num.size();i++)
		{
			if (num[i]>=maxVector.front())
			{
				maxVector.clear();
				maxVector.push_back(num[i]);
			}
			else if (num[i]>maxVector.back())
			{
				while (num[i] > maxVector.back())
					maxVector.pop_back();
				maxVector.push_back(num[i]);
			}
			else
				maxVector.push_back(num[i]);

			if (i > size - 1 && maxVector.size() > 0 && num[i - size] == maxVector.front())
				maxVector.erase(maxVector.begin());

			if (i >= size - 1)
				retVector.push_back(maxVector.front());
		}
	}
	return retVector;
}

解法二:
template
class CmaxInWindows
{
public:
	CmaxInWindows(int size)
	{
		maxValue = 0;
		winSize = size;
	}
	~CmaxInWindows(){}
	
	void push(T value)
	{
		if (stackA.size()+stackB.size()+1>winSize)
		{
			if (stackB.size()>0)
			{
				if (stackB.top() == stackMax.top())
					stackMax.pop();
				stackB.pop();
			}
			else
			{
				stackB.push(stackA.top());
				stackMax.push(stackA.top());
				stackA.pop();
				while (stackA.size()>0)
				{
					stackB.push(stackA.top());
					if (stackA.top() >= stackMax.top())
						stackMax.push(stackA.top());
					stackA.pop();
				}
				if (stackB.top()==stackMax.top())
					stackMax.pop();
				stackB.pop();
				maxValue = 0;
			}
		}

		maxValue = maxValue > value ? maxValue : value;
		stackA.push(value);
	}

	T getMax()
	{
		if (stackA.size() + stackB.size() < winSize) return 0;
		if (stackMax.size()>0)
			return maxValue > stackMax.top() ? maxValue : stackMax.top();
		else
			return maxValue;
	}
private:
	stack stackA;
	stack stackB;
	stack stackMax;
	T		 maxValue;
	int		 winSize;
};

vector maxInWindows(const vector& num, unsigned int size)//diy
{
	vector retVector;
	if (num.size() <= 0 || size <= 0 || num.size() < size) return retVector;
	CmaxInWindows maxWin(size);
	for (int i = 0; i < num.size();i++)
	{
		maxWin.push(num[i]);
		if (i >= size-1)
			retVector.push_back(maxWin.getMax());
	}
	return retVector;
}

 

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