当前位置:网站首页>Sword finger offer II 075 Array relative sort (custom sort, count sort)
Sword finger offer II 075 Array relative sort (custom sort, count sort)
2022-06-30 08:05:00 【Lafiteeee】
The finger of the sword Offer II 075. Array relative sort ( Custom sort 、 Count sorting )
Title Description

Method 1 : The simplest and easiest way to think of
- Use one
map<int, int> mpRecordarr1The number of occurrences of each number in - Traverse
arr2At the same time , To the answer arrayansAdd... In the looparr2[i], The number of cycles isarr1Is the number of times , With a variable at the same timecntRecord the sum of all occurrences . namelymp[arr2[i]], At the end of traversalarr1Appears inarr2The numbers in are in order - Use one
set<int> stStoragearr2Number in , Traversearr1, If it doesn't appear instin , Just add it to the answer arrayansBack ; - Come here ,
ansThe first... In the arraycntThe numbers are already in order , The following numbers are out of order , Just sort the following numberssort(ans.begin() + cnt, ans.end()).
class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
map<int, int> mp;
set<int> st;
for (int i = 0; i < arr1.size(); i++) {
mp[arr1[i]]++;
}
vector<int> tmp;
int cnt = 0;
for (auto k : arr2) {
st.insert(k);
int n = mp[k];
cnt += n;
while (n--) {
tmp.push_back(k);
}
}
for (auto num : arr1) {
if (st.find(num) == st.end()) {
tmp.push_back(num);
}
}
sort(tmp.begin() + cnt, tmp.end());
return tmp;
}
};
Method 2 : Directly customize the sorting of arrays
After reading the solution , To sum up . In fact, you can customize the sorting method , Yes arr1 Sort directly .
- Start with a hash table
map<int, int> mpRecordarr2All numbers inarr2[i]And its subscript position[i], That is to saymp[arr2[i]] = [i]; - Customize
sortComparison method in function , For two elementsa、b:- If a、b All in the hash table , explain a、b All in
arr2in , So compare their subscript positions , Elements with small subscripts are smaller ; - If a、b Are not in the hash table , Compare in normal size order ;
- If one is in a hash table , One is not in the hash table , Then the elements in the hash table are smaller .
- If a、b All in the hash table , explain a、b All in
- Direct pair
arr1Just sort it out . - Time complexity : O ( n l o g n ) O(nlogn) O(nlogn) Spatial complexity : O ( m ) O(m) O(m)
class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
unordered_map<int, int> mp;
for (int i = 0; i < arr2.size(); i++) {
mp[arr2[i]] = i;
}
sort(arr1.begin(), arr1.end(), [&](const int &a, const int &b) {
if (mp.count(a)) {
return mp.count(b) ? mp[a] < mp[b] : true;
} else {
return mp.count(b) ? false : a < b;
}
});
return arr1;
}
};
Method 3 : Count sorting ( Optimize method 1 )
Consider method one carefully , In fact, it is a bit like counting and sorting . Sort by count , There is no need to use a hash table to store the number of occurrences of an element , Instead, use an array . Topic arr2 The maximum value of elements in the array does not exceed 1000, So you can open a length of 1001 Array to record each number in arr1 Is the number of times , as well as arr2 The elements that appear in .
- Time complexity O ( n + m + 1001 ) O(n+m+1001) O(n+m+1001), Spatial complexity O ( 1001 ) O(1001) O(1001)
class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
vector<int> freq(1001);
for (auto num : arr1) {
freq[num]++;
}
vector<int> ans;
for (auto num : arr2) {
while (freq[num]) {
ans.push_back(num);
freq[num]--;
}
}
for (int i = 0; i < freq.size(); i++) {
while (freq[i]) {
ans.push_back(i);
freq[i]--;
}
}
return ans;
}
};
边栏推荐
- 牛客小白月賽52
- Development technology sharing of Jingtan NFT digital collection system
- 鲸探NFT数字臧品系统开发技术分享
- Acreems energy efficiency management platform escorts the power safety of high-rise residential areas
- HelloWorld
- 期末复习-PHP学习笔记2-PHP语言基础
- Experiment 2 LED button PWM 2021/11/15
- At the age of 25, I started to work in the Tiankeng industry with buckets. After going through a lot of hardships to become a programmer, my spring finally came
- 6月底了,可以开始做准备了,不然这么赚钱的行业就没你的份了
- CRM&PM如何帮助企业创造最优销售绩效
猜你喜欢

How to handle the expired data of redis and what are the elimination mechanisms?

25岁,从天坑行业提桶跑路,在经历千辛万苦转行程序员,属于我的春天终于来了
![November 22, 2021 [reading notes] - bioinformatics and functional genomics (Section 5 of Chapter 5 uses a comparison tool similar to blast to quickly search genomic DNA)](/img/de/7ffcc8d6911c499a9798ac9215c63f.jpg)
November 22, 2021 [reading notes] - bioinformatics and functional genomics (Section 5 of Chapter 5 uses a comparison tool similar to blast to quickly search genomic DNA)

期末复习-PHP学习笔记1

深度学习——网络中的网络以及1x1卷积

AcrelEMS能效管理平台为高层小区用电安全保驾护航

At the age of 25, I started to work in the Tiankeng industry with buckets. After going through a lot of hardships to become a programmer, my spring finally came

vulfocus入门靶机

深度学习——词汇表征

Deep learning -- sequence model and mathematical symbols
随机推荐
直击产业落地 | 飞桨重磅推出业界首个模型选型工具
Halcon12+vs2013 C # configuration
String and underlying character types of go data type
More, faster, better and cheaper. Here comes the fastdeploy beta of the low threshold AI deployment tool!
Analysis of cross clock transmission in tinyriscv
[flower carving experience] 14 line blank board pingpong library test external sensor module (one)
How to handle the expired data of redis and what are the elimination mechanisms?
F12抓包用于做postman接口测试的全过程解析
【NVMe2.0b 14-5】Firmware Download/Commit command
February 14, 2022 [reading notes] - life science based on deep learning Chapter 2 Introduction to deep learning (Part 1)
December 13, 2021 [reading notes] | understanding of chain specific database building
Arm debug interface (adiv5) analysis (I) introduction and implementation [continuous update]
深度学习——使用词嵌入and词嵌入特征
C. Fishingprince Plays With Array
The counting tool of combinatorial mathematics -- generating function
2022.01.20 [bug note] | qiime2: an error was encoded while running dada2 in R (return code 1)
Is it difficult to jump job ByteDance? With these skills, you can easily pass
January 23, 2022 [reading notes] - bioinformatics and functional genomics (Chapter 6: multiple sequence alignment)
Cadence innovus physical implementation series (I) Lab 1 preliminary innovus
Redis 的过期数据如何处理,淘汰机制都有那些?