在 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

更新日期: 2019 年 11 月 1 日

333 次檢視

啟動你的職業

完成課程即可獲得認證

開始
廣告