日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2024/9/30 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 给定数组Arr[n],O(n)时间内找出每个元素左侧所有元素中位置最靠近该元素且大于该元素的元素 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

    總結

    以上是生活随笔為你收集整理的给定数组Arr[n],O(n)时间内找出每个元素左侧所有元素中位置最靠近该元素且大于该元素的元素的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。