按频率对元素进行排序

Prerequisite:

先决条件:

  • Hashing data structure

    散列数据结构

  • How to write user-defined comparator for priority queue STL in C++?

    如何在C ++中为优先级队列STL编写用户定义的比较器?

  • How to sort a map based on values instead of value?

    如何根据值而不是值对地图排序?

Problem statement:

问题陈述:

Sort an array based on frequencies. The element having maximum frequency will come first. If two elements have the same frequency then the element coming first will appear first in the sorted array two.

根据频率对数组排序。 具有最大频率的元素将排在最前面。 如果两个元素具有相同的频率,则最先出现的元素将首先出现在排序数组2中。

Example:

例:

Input array:
[1, 2, 3, 2, 3, 2, 1]After sorting frequency wise:
[2, 2, 2, 1, 1, 3, 3]2 has the maximum frequency 
thus, it came first and since 1 and 3 have the same frequency, 
so, 1 came first preserving the order in the input array.

Solution:

解:

The idea is to create a hash table first which will store the frequency of unique elements. That can be created like below:

这个想法是首先创建一个哈希表,它将存储唯一元素的频率。 可以如下创建:

Hash function, h(x)=x but instead of storing key we will store the count

哈希函数h(x)= x,但是我们将存储计数而不是存储密钥

Initially, hash table is empty.

最初,哈希表为空。

For each key in input array,
Hash[key]++
End for

If we create the hash table from the above input array, it will be,

如果我们根据上面的输入数组创建哈希表,它将是

Key	Frequency
1	2
2	3
3	2

So now we need to sort the map based on the value instead of the key, but for the same frequencies, we need to preserve the key order(it’s order not key itself).

因此,现在我们需要根据值而不是键对映射进行排序,但是对于相同的频率,我们需要保留键顺序(该顺序不是键本身)。

To preserve the key order we require another hash table that would store the first position of the key. We will store that like below:

为了保留键顺序,我们需要另一个哈希表,该哈希表将存储键的第一个位置。 我们将像下面这样存储:

Say this hash table is named first_occurrence

假设此哈希表名为first_occurrence

For each key in input array,
If first_occurence[key]==0: //not assigned
first_occurence[key]=key index+1
End for

So after processing the input the hash table first_occurrence would be:

因此,在处理输入后,哈希表first_occurrence将是:

Key	First occurrence
1	1(0+1)
2	2(1+1
3	3(2+1)

So now rest of the task is to sort the hash table based on the map and based on first_occurrence hash table.

因此,现在剩下的任务是根据地图和基于first_occurrence哈希表对哈希表进行排序。

We will use the priority queue to sort this map based on our defined comparator where we will implement logic to sort by frequency value and first_occurrence hash table.

我们将使用优先级队列根据定义的比较器对此映射表进行排序,在该比较器中,我们将实现按频率值和first_occurrence哈希表排序的逻辑。

How to pass this in the comparator is our main challenge or area of our discussion?

如何在比较器中传递这一点是我们的主要挑战还是我们讨论的领域?

You can observe a thing that we have designed a class for this problem and kept the first_occurrence hash table as a data member, not any local member to a function. Thing is not the thing I do in general. So, there must be something, that made me design a class and bring the OOP concept within it. This is because I need to feed the first_occurrence hash table into the comparator and the comparator is a lambda function. Like below,

您会发现,我们已经为此问题设计了一个类,并将first_occurrence哈希表保留为数据成员,而不是函数的任何本地成员。 总的来说,这不是我要做的事情。 因此,必须有某种东西使我设计了一个类并将OOP概念引入其中。 这是因为我需要将first_occurrence哈希表提供给比较器,并且比较器是lambda函数。 像下面一样

auto comp=[](pair<int,int> a, pair<int,int> b){
//function body
}
But this time if you notice the implementation, we have 
auto comp=[this](pair<int,int> a, pair<int,int> b){
//function body
}

This helps you to pass the data members to the lambda function or it's known as capturing of the lambda function.

这可以帮助您将数据成员传递给lambda函数,或者称为捕获lambda函数

That's why we designed the class and made first_occurrence as data members to feed into the lambda function. Now we can perform our logic similarly as we do in comparators.

这就是为什么我们设计类并让first_occurrence作为数据成员馈入lambda函数的原因。 现在,我们可以像在比较器中一样执行逻辑。

The lambda comparator would be like below which will give us a sorted map based on our requirement via the priority_queue.

Lambda比较器如下所示,它将根据优先级通过priority_queue为我们提供排序的映射。

auto comp=[this](pair<int,int> a, pair<int,int> b){          
if(a.second<b.second)
return true;
else if(a.second>b.second)
return false;
else{
if(first_occurence[a.first]<first_occurence[b.first])
return false;
else
return true;
}
};

So after pushing all pairs(a map element is pair, <key, element>) we will have our priority queue as,

因此,在推送所有对之后(一个地图元素是pair,<key,element>),我们将拥有优先级队列,

Key	Frequency
2	3
1	2
3	2

Now, pop each element from the priority queue and append the key as many times as the frequency,

现在,从优先级队列中弹出每个元素,并按频率添加键多次,

So at iteration 1
We will pop <2,3>
So vector will be 2 2 2
So at iteration 2
We will pop <1,2>
So vector will be 2 2 2 1 1
So at iteration 3
We will pop <3,2>
So vector will be 2 2 2 1 1 3 3
Queue Is empty
So our sorted array based on frequency is
2 2 2 1 1 3 3

C++ implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;
class Includehelp {
public:
unordered_map<int, int> first_occurence;
void print(vector<int> arr)
{
for (auto i : arr) {
cout << i << " ";
}
cout << endl;
}
vector<int> sort_by_frequency(vector<int> arr)
{
//create the hashmap
unordered_map<int, int> mymap;
for (int i = 0; i < arr.size(); i++) {
mymap[arr[i]]++;
if (first_occurence[arr[i]] == 0)
first_occurence[arr[i]] = i + 1;
}
//now to sort based on frequency lets use priority queue
//comparator of priority queue using lambda function
auto comp = [this](pair<int, int> a, pair<int, int> b) {
if (a.second < b.second)
return true;
else if (a.second > b.second)
return false;
else {
if (first_occurence[a.first] < first_occurence[b.first])
return false;
else
return true;
}
};
priority_queue<pair<int, int>, vector<pair<int, int> >, decltype(comp)> pq(comp);
for (auto& ij : mymap) {
pq.push(ij);
}
//sorted outcome
vector<int> result;
while (!pq.empty()) {
pair<int, int> p = pq.top();
pq.pop();
int no = p.first;
int freq = p.second;
for (int i = 0; i < freq; i++)
result.push_back(no);
}
return result;
}
};
int main()
{
int n;
cout << "Enter number of elements\n";
cin >> n;
vector<int> arr(n, 0);
cout << "Enter the elements\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
Includehelp* obj = new Includehelp();
arr = obj->sort_by_frequency(arr);
cout << "Printing after sorting by frequency\n";
obj->print(arr);
return 0;
}

Output:

输出:

Enter number of elements
8
Enter the elements
1 2 3 1 2 3 4 5
Printing after sorting by frequency
1 1 2 2 3 3 4 5 

翻译自: https://www.includehelp.com/data-structure-tutorial/sort-elements-by-frequency.aspx

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/377958.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

二十、分水岭算法

一、基本原理 分水岭算法主要是基于距离变换&#xff08;distance transform&#xff09;&#xff0c;找到mark一些种子点&#xff0c;从这些种子点出发根据像素梯度变化进行寻找边缘并标记 分水岭&#xff1a;可以简单的理解成一座山&#xff0c;然后来洪水了&#xff0c;水开…

细数WOW里暴雪的“亲儿子”们

. 不知何时&#xff0c;魔兽世界的词汇中忽然出现了一个新玩意&#xff1a;亲儿子。虽说这个称呼现在大多是拿来调侃法爷的&#xff0c;但江山代有儿子出&#xff0c;各领风骚一两天&#xff0c;今天风光无限的法爷们也经历过被其他职业压得抬不起头的小媳妇生涯。那么今天…

Linux下串口ttyS2,ttyS3不能用的问题解决办法

PC104&#xff0c;Xlinux下&#xff0c;突然发现串口3,4不能用。。。 以为是硬件的问题&#xff0c;换成wince后&#xff0c;3,4工作正常&#xff0c;排除电路问题 在linux下查看dmesg: serial8250: ttyS0 at I/O 0x3f8 (irq 4) is a 16550Aserial8250: ttyS1 at I/O 0x2f8 (i…

安卓log.e函数打印示例_log1p()函数以及C ++中的示例

安卓log.e函数打印示例C log1p()函数 (C log1p() function) log1p() function is a library function of cmath header, it is used to get the natural logarithm (the base-e logarithm) of the one plus given value. It accepts a value (float, double, or long double) …

【C++grammar】C++类数据成员的初始化

目录1、类成员的就地初始化example2、构造函数初始化3、默认构造函数&#xff1a;Default Constructor4、举例5、成员的初始化方法的优先级1、类成员的就地初始化example class S { int m 7; // ok, copy-initializes m int n(7); // 错误&#xff1a;不允许用小括号初始化…

二十一、人脸检测

一、识别图像中的人脸 haarcascade_frontalface_alt_tree.xml lbpcascade_frontalcatface.xml GitHub上有Haar级联检测器源代码可自行下载&#xff0c;lbp级联检测器也一样有源码可自行下载 也一样 import cv2 as cv import numpy as npdef face_detect(image):gray cv.cvtC…

aspx特殊符号说明

http://www.cnblogs.com/GnagWang/archive/2010/07/14/1777130.html转载于:https://www.cnblogs.com/mingyongcheng/archive/2011/11/24/2261253.html

javascript运算符_JavaScript中的按位运算符

javascript运算符JavaScript按位运算符 (JavaScript Bitwise Operators) A lot of times you come across some strange operators where youre knocking your head to understand what is going on in the code. Almost all the programming languages have bitwise operators…

[置顶] Android的IPC访问控制设计与实现

3.3.1 IPC钩子函数设计与实现 IPC Binder是Android最重要的进程间通信机制&#xff0c;因此&#xff0c;必须在此实施强制访问控制。 1. 修改secuirty.h 打开终端shell&#xff0c;输入指令“cd /android4.0/kernel/goldfish/include/linux/vim security.h”&#xff0c;找到结…

TensorFlow在Anaconda环境下创建

一、我使用的是Anaconda自带的Jupyter编译器&#xff0c;详细的安装教程可以参考博文 二、之后打开Jupyter 三、进行测试 我的tensorflow使用的是2.0版本 import tensorflow.compat.v1 as tf tf.disable_v2_behavior()a tf.constant([1.0,2.0],name"a") b tf.co…

leetcode 654. 构造最大二叉树 思考分析

题目 给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下&#xff1a; 二叉树的根是数组中的最大元素。 左子树是通过数组中最大值左边部分构造出的最大二叉树。 右子树是通过数组中最大值右边部分构造出的最大二叉树。 通过给定的数组构建最大二叉树&am…

Memcache的命令以及状态监控

输入telnet 127.0.0.1 11211&#xff08;memcached默认端口为11211&#xff09; stats &#xff1a;使用stats命令查看当前memcache服务器的状态 pidmemcache服务器的进程IDuptime服务器已经运行的秒数time服务器当前的unix时间戳versionmemcache版本pointer_size当前操作系统 …

flush python_带有示例的Python File flush()方法

flush python文件flush()方法 (File flush() Method) flush() method is an inbuilt method in Python, it is used to clear/flush the internal buffer, it is best practice while working with fila handling in Python, the internal buffer can be cleared before writin…

c++ 请抛弃匈牙利命名法 - 变量命名代码风格的建议。

我只针对c码农们讲&#xff0c;其他语言不了解不过应该大同小异。曾几何时翻开21天学通c系列等脑残入门书&#xff0c;都以匈牙利命名法示人&#xff08;DWORD dwXXX, int nXXX, string strXXX)。现在我可以负责任的告诉你&#xff0c;把类型名写在前面屁用都没有&#xff0c;对…

Pycharm更换anaconda环境空间

一、File—>Settings 或者直接快捷键 CtrlAltS 二、找到自己的项目—>Project Interpreter—>找到需要使用的anaconda环境空间 三、Add Local 四、G:\Anaconda3\envs\mask_rcnn\python.exe一般anaconda的envs文件夹下&#xff0c;找到你的环境空间名称&#xff0c;…

android 应用demo截图

ksoap2实现天气预报 Frame 动画 baidu map 转载于:https://www.cnblogs.com/java20130726/archive/2011/11/28/3218328.html

leetcode 617. 合并二叉树 思考分析

题目 给定两个二叉树&#xff0c;想象当你将它们中的一个覆盖到另一个上时&#xff0c;两个二叉树的一些节点便会重叠。 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠&#xff0c;那么将他们的值相加作为节点合并后的新值&#xff0c;否则不为 NULL 的节点…

python 示例_带有示例的Python File write()方法

python 示例文件write()方法 (File write() Method) write() method is an inbuilt method in Python, it is used to write the content in the file. write()方法是Python中的内置方法&#xff0c;用于将内容写入文件中。 Syntax: 句法&#xff1a; file_object.write(text…

如何关掉Microsoft Office Click-to-Run服务

很烦&#xff0c;一开电脑就出现 一、打开任务管理器(CtrlShiftEsc) 服务—>打开服务 二、找到Microsoft Office Click-to-Run Service 右击&#xff0c;选择属性 三、禁用即可

[2013-08-19] nohup的使用

前几天自摆了一个乌龙。 由于项目中用到memcache&#xff1b;在linux机器上安装了该服务后&#xff0c;启动并且通过 & 设置到后台进程&#xff1b; 由于要指定某些服务端口&#xff0c;然后发现经常服务被“莫名其妙”地关闭了。我以为是别人手动关掉了&#xff0c;或者说…