LeetCode 75. 颜色分类

75. 颜色分类

解题思路

  • 统计频次: 使用数组 count 分别统计 0、1、2 出现的次数
  • 重写数组:根据统计结果,按顺序(0、1、2)将元素写回原数组 nums

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public void sortColors(int[] nums) {
int[] count = new int[3];

for(int num : nums) {
count[num] ++;
}

int startIndex = 0;
for(int i = 0; i < count.length; i ++) {
for(int j = 0; j < count[i]; j ++) {
nums[startIndex ++] = i;
}
}
}
}

LeetCode 75. 颜色分类
https://sowink.cn/2026/02/08/LeetCode-75-颜色分类/
作者
Xurx
发布于
2026年2月8日
许可协议