Sort Colors计数排序,计算每种color的个数 1234567891011121314 public void (int[] nums) { int[] colors = new int[3]; for (int i : nums) { colors[i]++; } int index = 0; int color = 0; for (int i : colors) { while (i-- > 0) { nums[index++] = color; } ++color; }} 可以用双指针的方法去做,把 0 全部交换到左边, 2 全部交换到右边。 12345678910111213141516171819202122 public void (int[] nums) { if (nums == null || nums.length == 0) return; int left = 0, right = nums.length - 1; for (int i = 0; i <= right;) { if (nums[i] == 2) { swap(nums, i, right); --right; } else if (nums[i] == 0) { swap(nums, i, left); ++left; ++i; } else ++i; }}public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp;} 赞微海报分享
近期评论