您的位置:首页 > 其它

lintcode:排颜色 II

2016-03-18 20:35 351 查看

排颜色 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
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]--;
}
}

}


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

九章看到两个指针的方法

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;
}

}


理解不透,脑子太笨。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: