📌  相关文章
📜  Array 中每个元素的较大元素计数

📅  最后修改于: 2021-10-27 08:06:02             🧑  作者: Mango

给定一个大小为N的整数数组arr ,任务是为每个元素找到大于它的元素数。
例子:

方法:使用 Map 存储每个数组元素的频率。反向迭代 Map 并存储每个元素的所有先前遍历元素(即大于它的元素)的频率总和。
下面的代码是上述方法的实现:

C++
// C++ implementation of the above approach
 
#include 
using namespace std;
 
void countOfGreaterElements(int arr[], int n)
{
    // Store the frequency of the
    // array elements
    map mp;
    for (int i = 0; i < n; i++) {
        mp[arr[i]]++;
    }
 
    int x = 0;
    // Store the sum of frequency of elements
    // greater than the current element
    for (auto it = mp.rbegin(); it != mp.rend(); it++) {
        int temp = it->second;
        mp[it->first] = x;
        x += temp;
    }
 
    for (int i = 0; i < n; i++)
        cout << mp[arr[i]] << " ";
}
 
// Driver code
int main()
{
 
    int arr[] = { 7, 9, 5, 2, 1, 3, 4, 8, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    countOfGreaterElements(arr, n);
 
    return 0;
}


Java
// Java implementation of the above approach
import java.util.*;
 
class GfG {
    public static void countOfGreaterElements(int arr[])
    {
        int n = arr.length;
 
        TreeMap mp = new TreeMap(Collections.reverseOrder());
 
        // Store the frequency of the
        // array elements
        for (int i = 0; i < n; i++) {
            mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
        }
 
        // Store the sum of frequency of elements
        // greater than the current element
        int x = 0;
        for (Map.Entry e : mp.entrySet()) {
            Integer temp = e.getValue();
            mp.put(e.getKey(), x);
            x += temp;
        }
 
        for (int i = 0; i < n; i++)
            System.out.print(mp.get(arr[i]) + " ");
    }
 
    public static void main(String args[])
    {
        int arr[] = { 7, 9, 5, 2, 1, 3, 4, 8, 6 };
        countOfGreaterElements(arr);
    }
}


Python 3
# Python 3 implementation of the above approach
 
def countOfGreaterElements(arr, n):
    # Store the frequency of the
    # array elements
    mp = {i:0 for i in range(1000)}
    for i in range(n):
        mp[arr[i]] += 1
 
    x = 0
    # Store the sum of frequency of elements
    # greater than the current element
    p = []
    q = []
    m = []
    for key, value in mp.items():
        m.append([key, value])
    m = m[::-1]
     
    for p in m:
        temp = p[1]
        mp[p[0]] = x
        x += temp
 
    for i in range(n):
        print(mp[arr[i]], end = " ")
 
# Driver code
if __name__ == '__main__':
    arr = [7, 9, 5, 2, 1, 3, 4, 8, 6]
    n = len(arr)
 
    countOfGreaterElements(arr, n)
 
# This code is contributed by Surendra_Gangwar


输出:
2 0 4 7 8 6 5 1 3

时间复杂度: O(N)