// o(n)在元素左侧最近位置找出比元素大的数.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stack>
#include <iterator>
using namespace std;
typedef struct withindex
{
int value;
int index;
}WithIndexSt;
typedef struct smallerNum
{
int curValue;
int index;
}SmallerNum;
void NearestNumberSmallerThanCurrent(int src[], int dst[], int n)
{
for (int idx = 0; idx < n; idx++)
dst[idx] = -1;
stack<SmallerNum> m_stack;
for (int i = 0; i < n; i++)
{
while(m_stack.size() > 0)
{
if (src[i] < m_stack.top().curValue)
{
dst[m_stack.top().index] = src[i];
m_stack.pop();
}
else
break;
}
SmallerNum newPair = {src[i],i};
m_stack.push(newPair);
}
}
void NearestNumberGreaterThanCurrent(int src[], int dst[], int n)
{
for (int idx = 0; idx < n; idx++)
dst[idx] = -1;
stack<WithIndexSt> m_stack;
for(int i = n - 1; i >= 0; i--)
{
while(!m_stack.empty())
{
if(m_stack.top().value < src[i])
{
dst[m_stack.top().index] = i;
m_stack.pop();
}
else
break;
}
WithIndexSt tmpst = {src[i], i};
m_stack.push(tmpst);
}
}
int main()
{
int src[] = {2, 9, 5, 2, 4, 1};
int nsize = sizeof(src)/sizeof(int);
int* dst = new int[nsize];
NearestNumberGreaterThanCurrent(src, dst, nsize);
copy(src, src+nsize, ostream_iterator<int>(cout, "\t"));
cout<<endl;
copy(dst, dst+nsize, ostream_iterator<int>(cout, "\t"));
cout<<endl;
delete[] dst;
cout << endl;
int* dst2 = new int[nsize];
NearestNumberSmallerThanCurrent(src, dst2, nsize);
copy(src, src+nsize, ostream_iterator<int>(cout, "\t"));
cout<<endl;
copy(dst2, dst+nsize, ostream_iterator<int>(cout, "\t"));
cout<<endl;
delete[] dst2;
return 0;
}
0(n)时间复杂度,找出最接近当前元素的 1)比当前元素大的左元素 2)比当前元素小的右元素
最新推荐文章于 2020-03-10 12:46:37 发布