Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Counting frequencies of array elements in C++: นับความถี่ของแต่ละค่าใน Array

กำหนด array ที่มีค่าซ้ำกัน หาความถี่ของแต่ละค่าที่แตกต่างกัน

ตัวอย่าง: {1,1,2,3,4,1,2,3} → 1:3, 2:2, 3:2, 4:1

วิธีแก้ปัญหา

O(n²) - Brute Force (visited array)

วน i, ถ้ายังไม่นับ วน j นับและ mark visited

O(n) - Hash Map (แนะนำ)

ใช้ unordered_map นับความถี่โดยตรง

ตัวอย่างโค้ด C++ (Hash Map)

#include <bits/stdc++.h>
using namespace std;

void frequency(int arr[], int n) {
    unordered_map freq;
    for(int i=0;i

Input

{1,2,3,1,2,3}

Output

Frequency of 1: 2
Frequency of 2: 2
Frequency of 3: 2