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

นับสมาชิกที่มีความถี่น้อยที่สุดใน Linked List ใน C++


งานคือนับจำนวนสมาชิกที่มีความถี่น้อยที่สุดใน Linked List ที่มีสมาชิกซ้ำ

Linked List เป็นโครงสร้างข้อมูลที่เก็บข้อมูลแบบลำดับ แต่ละโหนดลิงก์ไปยังโหนดถัดไป

ความถี่ของสมาชิกใน Linked List หมายถึงจำนวนครั้งที่สมาชิกนั้นปรากฏ ต้องนับสมาชิกที่มีความถี่น้อยที่สุด

เช่น Linked List: 1→1→3→1→3→4→6 ความถี่น้อยสุดคือ 1 มีสมาชิก 4 และ 6 รวม 2 ตัว

อินพุต − linked list 1→1→2→2→2→3→3

เอาต์พุต − count is 2

คำอธิบาย − ความถี่น้อยสุดคือ 2 มีสมาชิก 1 และ 3 รวม 2 ตัว

อินพุต − linked list = 1→2→3→2→4→2→5

เอาต์พุต − count is 4

แนวทาง

  • สร้าง Linked List และเพิ่มข้อมูล

  • ใช้ unordered_map นับความถี่แต่ละค่า

  • หาความถี่น้อยที่สุด

  • นับจำนวนสมาชิกที่มีความถี่เท่าค่าน้อยสุด

ตัวอย่าง

#include <iostream> 
#include <unordered_map> 
#include <climits> 
using namespace std; 

struct Node { int key; struct Node* next; }; 

void push(struct Node** head_ref, int new_key){ 
    struct Node* new_node = new Node; 
    new_node->key = new_key; 
    new_node->next = (*head_ref); 
    (*head_ref) = new_node; 
} 

int minimum(struct Node* head){ 
    unordered_map<int, int> mymap; 
    struct Node* current = head; 
    while (current != NULL){ mymap[current->key]++; current = current->next; } 
    int min = INT_MAX, count = 0; 
    for (auto it = mymap.begin(); it != mymap.end(); it++) if (it->second <= min) min = it->second; 
    for (auto it = mymap.begin(); it != mymap.end(); it++) if (it->second == min) count += (it->second); 
    return count; 
} 

int main(){ 
    struct Node* head = NULL; 
    push(&head, 30); push(&head, 50); push(&head, 61); push(&head, 40); push(&head, 30); 
    cout << "count is: " << minimum(head) << endl; 
    return 0; 
}

เอาต์พุต

count is: 3