在 C++ 中為陣列中的每一個元素尋找最近的更小值


我們將在本文中瞭解如何查詢陣列中每個元素最近的值。如果元素 x 擁有大於它且也存在於陣列中的下一個元素,則該元素將成為該元素的較大值。如果元素不存在,則返回 -1。假設陣列元素為 [10, 5, 11, 6, 20, 12],則較大的元素為 [11, 6, 12, 10, -1, 20]。由於 20 在陣列中沒有較大值,則列印 -1。

為解決此問題,我們將使用 C++ STL 中的設定。使用二叉樹方法實現集合。在二叉樹中,中序後繼始終是下一個較大元素。因此,我們可以在 O(log n) 時間內獲取元素。

示例

 即時演示

#include<iostream>
#include<set>
using namespace std;
void nearestGreatest(int arr[], int n) {
   set<int> tempSet;
   for (int i = 0; i < n; i++)
      tempSet.insert(arr[i]);
   for (int i = 0; i < n; i++) {
      auto next_greater = tempSet.upper_bound(arr[i]);
      if (next_greater == tempSet.end())
         cout << -1 << " ";
      else
         cout << *next_greater << " ";
   }
}
int main() {
   int arr[] = {10, 5, 11, 6, 20, 12};
   int n = sizeof(arr) / sizeof(arr[0]);
   nearestGreatest(arr, n);
}

輸出

11 6 12 10 -1 20

更新日期: 19-12-2019

137 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告