题解 | #牛的品种排序I#
牛的品种排序I
https://www.nowcoder.com/practice/e3864ed7689d460c9e2da77e1c866dce
一、知识点
数组 快排
二、解题思路
快速排序模板题
时间复杂度O(nlogn),空间复杂度O(1)
三、C++解法
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cows int整型vector
* @return int整型vector
*/
vector<int> sortCows(vector<int>& cows) {
int len = cows.size();
qucikSort(cows, 0, len - 1);
return cows;
}
void qucikSort(vector<int>& cows, int left, int right) {
if (left < right) {
int pos = findPos(cows, left, right);
qucikSort(cows, left, pos - 1);
qucikSort(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;
}
};
#在找工作求抱抱#高频算法Top202-题解 文章被收录于专栏
手把手带你刷题
查看6道真题和解析