http://blog.youkuaiyun.com/yysdsyl/article/details/5419149#cpp
题目:
给定数组Arr[n],对于其中的每个元素Arr[i](0=<i<n),在Arr[0...i-1]中找到元素Arr[k],Arr[k]满足Arr[k]>Arr[i],并且i-k值最小(即最靠近)。
要求O(n)时间内找出Arr中所有元素对应的Arr[k]的位置。
ex,
src[]: 9, 5, 2, 4, 7
dst[]: -1,0, 1, 1, 0
思路:
借助于栈来实现,从后向前遍历数组,while栈顶元素小于当前遍历的数组元素,则更新dst,并pop。
参见下面代码
代码:
- #include <iostream>
- #include <stack>
- #include <iterator>
- using namespace std;
- typedef struct withindex
- {
- int value;
- int index;
- }WithIndexSt;
- void NearestNumberGreaterThanCurrent(int src[], int dst[], int n)
- {
- 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);
- }
- dst[0] = -1;
- }
- int main()
- {
- int src[] = {9, 5, 2, 4, 7};
- 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"));
- delete[] dst;
- return 0;
- }
上面的思路比较复杂,我是这样实现的:
void minDist(int *a, int *b, int n) {
b[0] = -1;
for (int i = 1; i <n ;++i) {
int j = i - 1;
while(j >=0 && a[j] <= a[i])
j = b[j];
b[i] = j;
}
}