Блог пользователя silentknight00

Автор silentknight00, история, 6 лет назад, По-английски

Given an array [1,3,4,2] we should get an array [0,0,0,2]. Can someone suggest a quick method for doing this

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
6 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

This is essentially the inversion problem which can be solved using segment tree or binary indexes tree in O(nlogn). ( You can search for it online)

»
6 лет назад, # |
Rev. 3   Проголосовать: нравится +10 Проголосовать: не нравится

Iterate from the left and imagine the array is the skyscrapers with height a[i]. Now we want to maintain all skyscrapers visible from i. To do so just maintain a stack. O(n).

stack<int>X;
for (int i = 0; i < n; i++)
{
	while (!X.empty() && a[X.top()] <= a[i])
	{
		X.pop();
	}
	if (X.empty())
		ans[i] = -1;
	else
		ans[i] = X.top();
	X.push(i);
}