当前位置:网站首页>LeetCode 324. 摆动排序 II
LeetCode 324. 摆动排序 II
2022-07-03 08:49:00 【Sasakihaise_】
【计数排序】因为nums[i]的范围在5000内,所以可以考虑计数排序,虽然需要O(m)的空间复杂度,但是可以保证O(n)的时间复杂度。具体做法就是,先统计每个出现的次数,从前往后先把奇数位置放上最大的一半元素,然后从头到尾再把偶数位置放上次大的元素。
class Solution {
// 计数排序 10:46 10:49
public void wiggleSort(int[] nums) {
int[] cnt = new int[5001];
for (var x: nums) {
cnt[x]++;
}
int j = 5000, n = nums.length;
for (var i = 1; i < n; i += 2) {
while (cnt[j] == 0) {
j--;
}
nums[i] = j;
cnt[j]--;
}
for (var i = 0; i < n; i += 2) {
while (cnt[j] == 0) {
j--;
}
nums[i] = j;
cnt[j]--;
}
}
}
边栏推荐
猜你喜欢
How to place the parameters of the controller in the view after encountering the input textarea tag in the TP framework
Binary to decimal, decimal to binary
PHP uses foreach to get a value in a two-dimensional associative array (with instances)
Deeply understand the underlying data structure of MySQL index
SQL statement error of common bug caused by Excel cell content that is not paid attention to for a long time
Binary tree traversal (first order traversal. Output results according to first order, middle order, and last order)
单调栈-84. 柱状图中最大的矩形
数位统计DP AcWing 338. 计数问题
[concurrent programming] explicit lock and AQS
二进制转十进制,十进制转二进制
随机推荐
【Rust笔记】02-所有权
SQL statement error of common bug caused by Excel cell content that is not paid attention to for a long time
UE4 source code reading_ Bone model and animation system_ Animation process
请求参数的发送和接收
DOM render mount patch responsive system
22-06-28 Xi'an redis (02) persistence mechanism, entry, transaction control, master-slave replication mechanism
The method for win10 system to enter the control panel is as follows:
JS non Boolean operation - learning notes
Life cycle of Servlet
Redis cluster series 4
Monotonic stack -42 Connect rainwater
Talking about: is the HashSet set ordered or disordered /hashset set unique, why can we store elements with the same content
cres
状态压缩DP AcWing 91. 最短Hamilton路径
[concurrent programming] explicit lock and AQS
Alibaba canal actual combat
数据库原理期末复习
XPath实现XML文档的查询
First Servlet
Escape from heaven and forget what he suffered. In ancient times, it was called the punishment of escape from heaven. Article collection