在 C++ STL 中使用集合計數右側較小的元素
在本教程中,我們將討論如何在 C++ STL 中利用集合來計算右側較小的元素。
為此,我們將提供一個數組。我們的任務是構建一個新陣列,並在當前元素的位置新增右側較小的元素的數量。
示例
#include <bits/stdc++.h> using namespace std; void count_Rsmall(int A[], int len){ set<int> s; int countSmaller[len]; for (int i = len - 1; i >= 0; i--) { s.insert(A[i]); auto it = s.lower_bound(A[i]); countSmaller[i] = distance(s.begin(), it); } for (int i = 0; i < len; i++) cout << countSmaller[i] << " "; } int main(){ int A[] = {12, 1, 2, 3, 0, 11, 4}; int len = sizeof(A) / sizeof(int); count_Rsmall(A, len); return 0; }
輸出
6 1 1 1 0 1 0
廣告