小作业:关于 leetcode 75题,计数排序的优化
来源:3-5 三路快排partition思路的应用 Sort Color

慕斯902xzxc_das
2021-11-16
class Solution {
public void sortColors(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
int[] cnt = new int[3];
// cnt[] 用索引来代表 nums[] 数组中的数字,用索引位置上的值来表示该数字出现的频率
// 如: cnt[nums[i]] 表示 nums[i] 出现在 nums[] 中出现的频率
for (int i = 0; i < nums.length; i++) {
cnt[nums[i]]++;
}
// l 表示存放数字 i 的左边界
int l = 0;
// 遍历 cnt[] 数组, 获取0~3数字出现的频率
// i 表示 nums[] 数组中相应的数字,数字 i 的所在范围是 [l...r)
for (int i = 0; i < 3; i++) {
// r 表示存放数字 i 的右边界 + 1
int r = l + cnt[i];
while (l < r) {
nums[l++] = i;
}
// 退出循环时, l 指向的位置为本轮循环中数字 i + 1 或者是下一轮循环中数字 i 的左边界
}
}
}
写回答
1回答
-
赞!继续加油呀!:)
012021-11-16
相似问题