📜  使用C++ STL中的Set计数反转

📅  最后修改于: 2021-05-30 13:00:28             🧑  作者: Mango

数组的反转计数指示–数组要排序的距离(或距离)。如果数组已经排序,则反转计数为0。如果数组以相反顺序排序,则反转计数为最大。

Two elements a[i] and a[j] form an inversion if 
     a[i] > a[j] and i < j. For simplicity, we may 
     assume that all elements are unique.

     Example:
     Input:  arr[] = {8, 4, 2, 1}
     Output: 6
     Given array has six inversions (8,4), (4,2),
     (8,2), (8,1), (4,1), (2,1).     

我们已经讨论了以下方法。
1)基于朴素和合并排序的方法。
2)基于AVL树的方法。

在这篇文章中,讨论了在C++ STL中使用Set的方法2的简单实现。

1) Create an empty Set in C++ STL (Note that a Set in C++ STL is 
   implemented using Self-Balancing Binary Search Tree). And insert
   first element of array into the set.

2) Initialize inversion count as 0.

3) Iterate from 1 to n-1 and do following for every element in arr[i]
     a) Insert arr[i] into the set.
     b) Find the first element greater than arr[i] in set
        using upper_bound() defined Set STL.
     c) Find distance of above found element from last element in set
        and add this distance to inversion count.

4) Return inversion count.
// A STL Set based approach for inversion count 
#include
using namespace std;
  
// Returns inversion count in arr[0..n-1]
int getInvCount(int arr[],int n)
{
    // Create an empty set and insert first element in it
    multiset set1;
    set1.insert(arr[0]);
  
    int invcount = 0; // Initialize result
  
    multiset::iterator itset1; // Iterator for the set
  
    // Traverse all elements starting from second
    for (int i=1; i

输出:

Number of inversions count are : 6

请注意,上述实现的最坏情况下的时间复杂度是O(n 2 ),因为STL中的距离函数需要O(n)时间最坏的情况,但是此实现比其他实现简单得多,并且平均而言要比Naive方法花费更少的时间。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”