📌  相关文章
📜  程序使用C++中的map查找向量中每个元素的频率

📅  最后修改于: 2021-05-30 05:45:47             🧑  作者: Mango

给定向量vec ,任务是使用映射图找到vec的每个元素的频率。
例子:

方法:
我们可以使用给定的四个步骤有效地找到向量中元素的频率:

  1. 遍历给定向量vec的元素。
  2. 检查地图中是否存在当前元素。
  3. 如果存在,则更新当前元素的频率,否则插入频率为1的元素,如下所示:
  4. 遍历地图,并打印存储为映射值的每个元素的频率。

下面是上述方法的实现:

CPP
#include 
using namespace std;
 
void printFrequency(vector vec)
{
    // Define an map
    map M;
 
    // Traverse vector vec check if
    // current element is present
    // or not
    for (int i = 0; vec[i]; i++) {
 
        // If the current element
        // is not found then insert
        // current element with
        // frequency 1
        if (M.find(vec[i]) == M.end()) {
            M[vec[i]] = 1;
        }
 
        // Else update the frequency
        else {
            M[vec[i]]++;
        }
    }
 
    // Traverse the map to print the
    // frequency
    for (auto& it : M) {
        cout << it.first << ' '
             << it.second << '\n';
    }
}
 
// Driver Code
int main()
{
    vector vec = { 1, 2, 2, 3, 1, 4, 4, 5 };
 
    // Function call
    printFrequency(vec);
    return 0;
}


输出:
1 2
2 2
3 1
4 2
5 1

复杂度分析:
时间复杂度: O(n log n)
对于大小为n的给定向量,我们对其进行一次迭代,并且在映射中搜索元素的时间复杂度为O(log n)。因此时间复杂度为O(n log n)
空间复杂度: O(n)
对于大小为n的给定向量,我们使用了一个额外的映射,该映射最多可以具有n个键值,因此空间复杂度为O(n)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。