lintcode:排颜色 II

时间:2023-03-10 05:59:31
lintcode:排颜色 II

排颜色 II

给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序。

样例

给出colors=[3, 2, 2, 1, 4]k=4, 你的代码应该在原地操作使得数组变成[1, 2, 2, 3, 4]

解题

直接快排

class Solution {
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
public void sortColors2(int[] colors, int k) {
// write your code here
sort(colors,0,colors.length - 1);
}
public void sort(int[] A,int low,int high){
if(low >= high)
return ;
int i = low;
int j = high;
int tmp = A[low];
while(i<j){
while(i<j && A[j]>tmp) j--;
if(i<j){
A[i] = A[j];
i++;
}
while(i<j && A[i]<= tmp) i++;
if(i<j){
A[j] = A[i];
j--;
}
}
A[i] = tmp;
sort(A,low,i-1);
sort(A,i+1,high);
}
}

Java Code

标记法,先统计各个颜色的次数,然后根据数组更改次数

class Solution {
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
public void sortColors2(int[] colors, int k) {
// write your code here
int[] flag = new int[k+1];
for(int i = 0;i<colors.length;i++){
flag[colors[i]]++;
}
int c = 1;
for(int i = 0;i<colors.length;i++){
while(flag[c]==0){// 颜色可能为0 的比较多
c++;
}
colors[i] = c;
flag[c]--;
}
} }

只有三种颜色的排序 的时候,但是当有多个的时候判断情况太多。

九章看到两个指针的方法

class Solution {
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
public void sortColors2(int[] colors, int k) {
int count = 0;
int start = 0;
int end = colors.length-1;
while (count < k) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE; for (int i = start; i <= end; i++) {
min = Math.min(min, colors[i]);
max = Math.max(max, colors[i]);
}
int left = start;
int right = end;
int cur = left;
while(cur <= right) {
if (colors[cur] == min) {
swap(left, cur, colors);
cur++;
left++;
} else if (colors[cur] > min && colors[cur] < max) {
cur++;
} else {
int tmp = colors[cur];
swap(cur, right, colors);
right--;
}
}
count += 2;
start = left;
end = right;
}
} void swap(int left, int right, int[] colors) {
int tmp = colors[left];
colors[left] = colors[right];
colors[right] = tmp;
} }

理解不透,脑子太笨。