解法一:计数排序

统计出现频率,然后原地修改。常数级空间但是需要两趟扫描。

  1. class Solution {
  2. public void sortColors(int[] nums) {
  3. int[] cnt = new int[3];
  4. for (int i : nums) {
  5. ++cnt[i];
  6. }
  7. int index = 0;
  8. for (int color = 0; color < 3; ++color) {
  9. for (int i = 0; i < cnt[color]; ++i) {
  10. nums[index++] = color;
  11. }
  12. }
  13. }
  14. }

解法二:双指针

参考官方题解:https://leetcode-cn.com/problems/sort-colors/solution/yan-se-fen-lei-by-leetcode-solution/

  1. class Solution {
  2. public void sortColors(int[] nums) {
  3. int p0, p1;
  4. p0 = p1 = 0;
  5. for (int i = 0; i < nums.length; ++i) {
  6. switch (nums[i]) {
  7. case 1:
  8. nums[i] = nums[p1];
  9. nums[p1] = 1;
  10. ++p1;
  11. break;
  12. case 0:
  13. nums[i] = nums[p1];
  14. nums[p1] = 1;
  15. nums[p0] = 0;
  16. ++p0;
  17. ++p1;
  18. }
  19. }
  20. }
  21. }