描述
给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序。
You are not suppose to use the library's sort function for this problem.
k <= n
您在真实的面试中是否遇到过这个题? 是
样例
给出colors=[3, 2, 2, 1, 4]
,k=4
, 你的代码应该在原地操作使得数组变成[1, 2, 2, 3, 4]
挑战
一个相当直接的解决方案是使用计数排序扫描2遍的算法。这样你会花费O(k)的额外空间。你否能在不使用额外空间的情况下完成?
方法一:需要O(k)的空间
代码:
class Solution {
public:
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
void sortColors2(vector<int> &colors, int k) {
// write your code here
map<int, int> imap;
for(int i=0; i<colors.size(); i++){
imap[colors[i]] += 1;//统计每个数字出现的次数
}
int m = 0;
for(int i=0; i<imap.size(); i++){
for(int j=0; j<imap[i]; j++){
colors[m++] = i;//将每个数字从0到k输出
}
}
}
};
方法二:不占用外部空间,还没理解!!!!!
首先for循环遍历一遍原来的数组,如果扫到a[i],首先检查a[a[i]]是否为正数,如果是把a[a[i]]移动a[i]存放起来,然后把a[a[i]]记为-1(表示该位置是一个计数器,计1)。 如果a[a[i]]是负数,那么说明这一个地方曾经已经计数了,那么把a[a[i]]计数减一,并把color[i] 设置为0 (表示此处已经计算过),然后重复向下遍历下一个数,这样遍历原数组所有的元素过后,数组a里面实际上存储的每种颜色的计数,然后我们倒着再输出每种颜色就可以得到我们排序后的数组。
代码:
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
if(colors == null || colors.length == 0) return;
int index = 0;
while(index < colors.length){
if(colors[index] <= 0){
index++;
}else{
if(colors[colors[index] - 1] <= 0){
colors[colors[index] - 1]--;
colors[index] = 0;
index++;
}else{
int temp = colors[index] - 1;
swap(colors , index , colors[index] - 1);
colors[temp] = -1;
}
}
}
int i = colors.length - 1;
while(k > 0){
for(int j = 0;j>colors[k - 1];j--){
colors[i--] = k;
}
k--;
}
}
public void swap(int[] colors , int start , int end){
int temp = colors[start];
colors[start] = colors[end];
colors[end] = temp;
return ;
}
}