题解 | #牛的品种排序II#
牛的品种排序II
https://www.nowcoder.com/practice/43e49fbb98b4497ba46e185918188b1c
一、知识点
数组 排序
二、解题思路
1.思路一 快速排序
将数组进行快速排序
时间复杂度O(nlogn),空间复杂度O(1)。
2.思路二 计数排序
新建一个hash映射,遍历原数组统计0、1、2分别出现的次数。
最后根据hash构造新数组。
时间复杂度O(n),空间复杂度O(n)。
三、C++解法
1.快排
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cows int整型vector
* @return int整型vector
*/
vector<int> sortCows(vector<int>& cows) {
// write code here
int len = cows.size();
quickSort(cows, 0, len - 1);
return cows;
}
void quickSort(vector<int>& cows, int left, int right) {
if (left < right) {
int pos = findPos(cows, left, right);
quickSort(cows, left, pos - 1);
quickSort(cows, pos + 1, right);
}
}
int findPos(vector<int>& cows, int left, int right) {
int first = cows[left];
while (left < right) {
while (left < right && cows[right] >= first) {
right --;
}
swap(cows[left], cows[right]);
while (left < right && cows[left] <= first) {
left ++;
}
swap(cows[left], cows[right]);
}
return left;
}
};
2.计数排序
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cows int整型vector
* @return int整型vector
*/
vector<int> sortCows(vector<int>& cows) {
int len = cows.size();
unordered_map<int, int> hash;
for (int i = 0; i < len; i ++) {
hash[cows[i]] ++;
}
int idx = 0;
for (int i = 0; i < 3; i ++) {
while (hash[i]) {
cows[idx++] = i;
hash[i]--;
}
}
return cows;
}
};
#在找工作求抱抱#高频算法Top202-题解 文章被收录于专栏
手把手带你刷题
查看12道真题和解析