用 C++ 統計連結串列中最小頻率元素的個數
給定的任務是在給定的包含重複元素的連結串列中統計最小頻率元素的個數。
連結串列是一種資料結構,其中資料按順序儲存,類似於列表,每個元素都連結到下一個元素。
連結串列中元素的頻率是指該元素在連結串列中出現的次數。根據問題,我們需要統計連結串列中的最小頻率。
假設我們有一個連結串列: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
解釋 −
在上述示例中,最小頻率為 1,並且有 4 個元素的頻率最小,即 1、3、4 和 5,所以個數為 4。
下面程式中使用的方案如下
定義一個連結串列並將元素推入連結串列。
在 `minimum` 函式中,為了找到最小頻率元素的個數,宣告一個名為 `mymap` 的對映(map)來儲存數字的頻率。
遍歷列表並將元素的頻率(出現次數)儲存在 `mymap` 中。
在我們找到頻率並將頻率儲存在 `mymap` 中後,找到最小頻率。
統計 `mymap` 中出現最小頻率的次數。
返回計數。
示例
#include <iostream>
#include <unordered_map>
#include <climits>
using namespace std;
struct Node {
int key;
struct Node* next;
};
// to push the values in the stack
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;
}
// Function to count minimum frequency elements
// in the linked list
int minimum(struct Node* head){
// Store frequencies of all nodes.
unordered_map<int, int> mymap;
struct Node* current = head;
while (current != NULL){
int value = current->key;
mymap[value]++;
current = current->next;
}
// Find min frequency
current = head;
int min = INT_MAX, count = 0;
for (auto it = mymap.begin(); it != mymap.end(); it++){
if (it->second <= min){
min = it->second;
}
}
// Find count of min frequency elements
for (auto it = mymap.begin(); it != mymap.end(); it++){
if (it->second == min){
count += (it->second);
}
}
return count;
}
int main(){
/* Starting with an empty list */
struct Node* head = NULL;
int x = 21;
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP