给定数组Arr[n],O(n)时间内找出每个元素左侧所有元素中位置最靠近该元素且大于该元素的元素

来源:互联网 发布:for vb 编辑:程序博客网 时间:2024/05/18 17:24

http://blog.csdn.net/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。

参见下面代码

 

 

代码:

[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <stack>  
  3. #include <iterator>  
  4.   
  5. using namespace std;  
  6.   
  7. typedef struct withindex  
  8. {  
  9.     int value;  
  10.     int index;  
  11. }WithIndexSt;  
  12.   
  13. void NearestNumberGreaterThanCurrent(int src[], int dst[], int n)  
  14. {  
  15.     stack<WithIndexSt> m_stack;  
  16.     for(int i = n - 1; i >= 0; i--)  
  17.     {  
  18.         while(!m_stack.empty())  
  19.         {  
  20.             if(m_stack.top().value < src[i])  
  21.             {  
  22.                 dst[m_stack.top().index] = i;  
  23.                 m_stack.pop();  
  24.             }  
  25.             else  
  26.                 break;  
  27.         }  
  28.         WithIndexSt tmpst = {src[i], i};  
  29.         m_stack.push(tmpst);  
  30.     }  
  31.     dst[0] = -1;  
  32. }  
  33.   
  34. int main()  
  35. {  
  36.     int src[] = {9, 5, 2, 4, 7};  
  37.     int nsize = sizeof(src)/sizeof(int);  
  38.     int* dst = new int[nsize];  
  39.     NearestNumberGreaterThanCurrent(src, dst, nsize);  
  40.     copy(src, src+nsize, ostream_iterator<int>(cout, "/t"));  
  41.     cout<<endl;  
  42.     copy(dst, dst+nsize, ostream_iterator<int>(cout, "/t"));  
  43.     delete[] dst;  
  44.     return 0;  
  45. }  

上面的思路比较复杂,我是这样实现的:

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;    }}


原创粉丝点击