问题:给定一个数组,求得每个元素左右两边离它最近的小于它的数,要求时间复杂度O(N)
若是求两边比它小的,则用单调递增栈
若是求两边比它大的,则用单调递减栈
pair<int, int> *GetResult(vector<int> arr)
{
pair<int, int> *res = new pair<int, int>[arr.size()];
stack<vector<int>> st;
for (int i = 0; i < arr.size(); i++)
{
while (!st.empty() && arr[st.top()[0]] > arr[i])
{
vector<int> temp = st.top();
st.pop();
for (int k = 0; k < temp.size(); k++)
{
res[temp[k]].second = i;
if (!st.empty())
{
res[temp[k]].first = st.top().back();
}
else
{
res[temp[k]].first = -1;
}
}
}
if (!st.empty()&&arr[st.top()[0]] == arr[i])
{
st.top().push_back(i);
}
else
{
vector<int> temp;
temp.push_back(i);
st.push(temp);
}
}
while (!st.empty())
{
vector<int> temp = st.top();
st.pop();
for (int k = 0; k < temp.size(); k++)
{
res[temp[k]].second = -1;
if (!st.empty())
{
res[temp[k]].first = st.top().back();
}
else
{
res[temp[k]].first = -1;
}
}
}
return res;
}
其中pair结构第一个元素是左边离它最近且小于它的数的索引,第二个元素是右边离它最近且小于它的数的索引
且程序中的所有数据结构存储的都是原来数组的索引。