文章目录
- 1. 归并排序
- 2. 计数
- 3. 按照题目要求,原地腾挪
给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
必须在不使用库内置的 sort 函数的情况下解决这个问题。
https://leetcode.cn/problems/sort-colors/description/?envType=study-plan-v2&envId=top-100-liked
1. 归并排序
class Solution {
public void doSort(int[] nums, int[] help,
int start, int end) {
if (start >= end) {
return;
}
int mid = (start + end) / 2;
doSort(nums, help, start, mid);
doSort(nums, help, mid + 1, end);
int left = start;
int right = mid + 1;
int idx = left;
while (left <= mid && right <= end) {
if (nums[left] <= nums[right]) {
help[idx++] = nums[left++];
} else {
help[idx++] = nums[right++];
}
}
while (left <= mid) {
help[idx++] = nums[left++];
}
while (right <= end) {
help[idx++] = nums[right++];
}
for (int i = start; i <= end; i++) {
nums[i] = help[i];
}
}
public void sortColors(int[] nums) {
int[] help = new int[nums.length];
doSort(nums, help, 0, nums.length - 1);
}
}
2. 计数
class Solution {
public void sortColors(int[] nums) {
int[] arr = new int[]{0,0,0};
for (int i = 0; i < nums.length; i++) {
arr[nums[i]] +=1;
}
int idx = 0;
for (int i = 0; i < arr.length; i++) {
while(arr[i]-- > 0) {
nums[idx++] = i;
}
}
}
}
3. 按照题目要求,原地腾挪
class Solution {
private void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
/**
* zero side [0,zeroSide)
* one side (zeroRSide, oneRSide)
* two side (oneRSide, twoRSide)
*/
public void sortColors(int[] nums) {
int zeroRSide = 0;
int oneRSide = 0;
int twoRSide = 0;
int cursor = 0;
while (cursor < nums.length) {
if (nums[cursor] == 0) {
swap(nums, cursor, oneRSide);
twoRSide += 1;
swap(nums, oneRSide, zeroRSide);
zeroRSide += 1;
oneRSide += 1;
} else if (nums[cursor] == 1) {
swap(nums, cursor, oneRSide);
oneRSide+=1;
twoRSide+=1;
} else {
twoRSide += 1;
}
cursor += 1;
}
}
}