给定一个包含红色、绿色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、绿色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、绿色和蓝色。
示例 1:
输入:nums = [2,0,2,1,1,0]
输出:[0,0,1,1,2,2]
示例 2:
输入:nums = [2,0,1]
输出:[0,1,2]
示例 3:
输入:nums = [0]
输出:[0]
示例 4:
输入:nums = [1]
输出:[1]
提示:
n == nums.length
1 <= n <= 300
nums[i] 为 0、1 或 2
package com.loo;
import java.util.Map;
import java.util.HashMap;
import java.util.Arrays;
public class SortColor {
public static void main(String[] args) {
int[] nums0 = new int[] {2, 0, 2, 1, 1, 0};
int[] match0 = new int[] {0, 1 , 2};
int[] nums = new int[] {2, 0, 2, 5 , 3, 1, 4, 1, 0 , 7, 4 , 6 , 1 , 3};
int[] match = new int[] {0, 1 , 2 ,3 , 4 , 5 , 6 , 7};
System.out.println(Arrays.toString(getSortColor(nums0 , match0)));
System.out.println(Arrays.toString(getSortColor1(nums , match)));
}
// 对已知少量的 match 可以这样算,但如果考虑到 match 可变,这里适应性比较差
public static int[] getSortColor(int[] arr , int[] match) {
if (arr == null || arr.length <= 1 ||
match == null || match.length == 0) {
return arr;
}
int N = arr.length;
Map<Integer , Integer> map0 = new HashMap<Integer , Integer>();
Map<Integer , Integer> map1 = new HashMap<Integer , Integer>();
Map<Integer , Integer> map2 = new HashMap<Integer , Integer>();
for (int i=0;i<N;i++) {
if (arr[i] == match[0]) {
map0.put(i , match[0]);
} else if (arr[i] == match[1]) {
map1.put(i , match[1]);
} else if (arr[i] == match[2]) {
map2.put(i , match[2]);
}
}
int[] result = new int[N];
int index = 0;
for (int key : map0.keySet()) {
result[index++] = map0.get(key);
}
for (int key : map1.keySet()) {
result[index++] = map1.get(key);
}
for (int key : map2.keySet()) {
result[index++] = map2.get(key);
}
return result;
}
// getSortColor1 的 match 自适应可变长度
public static int[] getSortColor1(int[] arr , int[] match) {
if (arr == null || arr.length <= 1 ||
match == null || match.length == 0) {
return arr;
}
int N = arr.length;
// 相当于桶排序,这里 count 只作统计 ,计算在 arr 中分别有
// match[0 --- match.length-1] 多少个,对应记录个数在
// count[0 --- match.length-1] 中
int[] count = new int[match.length];
for (int i=0;i<N;i++) {
int index = getIndexNum(match , arr[i]);
if (index != -1 && index < count.length) {
count[index]++;
}
}
int[] result = new int[arr.length];
int index = 0;
for (int i=0;i<count.length;i++) {
if (count[i] > 0) {
for (int j=0;j<count[i];j++) {
result[index++] = match[i];
}
}
}
return result;
}
public static int getIndexNum(int[] match , int index) {
if (match == null || match.length == 0) {
return -1;
}
for (int i=0;i<match.length;i++) {
if (index == match[i]) {
return i;
}
}
return -1;
}
}