按頻率對元素進行排序

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.pswp.cn/news/377958.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377958.shtml
英文地址,請注明出處:http://en.pswp.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;或者說…