用 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