目录
75. 颜色分类
解析
题解
class Solution {
public:
void sortColors(vector<int>& nums) {
// 专题七_分治-快排_颜色划分_C++
// [0 - left] : 全是 0
// [left+1 - i-1] : 全是 1
// [i - right-1] : 未扫描的区域
// [right - n--1] : 全是 2
int left = -1, i = 0, right = nums.size();
while(i < right)
{
if (nums[i] == 0) swap(nums[++left], nums[i++]);
else if (nums[i] == 1) i++;
else swap(nums[i], nums[--right]);
}
}
};
912. 排序数组
解析
题解
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
// 46.专题七_分治-快速_快速排序_C++
srand(time(NULL));
qsort(nums, 0, nums.size() - 1);
return nums;
}
void qsort(vector<int>& nums, int l, int r)
{
if (l >= r) return;
// 数组分三块
int key = getRandom(nums, l, r);
int i = l, left = l - 1, right = r + 1;
while (i < right)
{
if (nums[i] < key) swap(nums[i++], nums[++left]);
else if (nums[i] == key) i++;
else swap(nums[i], nums[--right]);
}
// [l, left] [left + 1, right - 1] [right, r]
qsort(nums, l, left);
qsort(nums, right, r);
}
int getRandom(vector<int>& nums, int left, int right)
{
int r = rand();
return nums[r % (right - left + 1) + left];
}
};
215. 数组中的第K个最大元素
解析
题解
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
// 47.专题七_分治-快排_快速选择算法_C++
srand(time(NULL));
return qsort(nums, 0, nums.size() - 1, k);
}
int qsort(vector<int>& nums, int l, int r, int k)
{
if (l == r) return nums[l];
// 1. 随机选择基准元素
int key = GetRandom(nums, l, r);
// 2. 根据基准元素将数组分三块
int i = l, left = l - 1, right = r + 1;
while (i < right)
{
if (nums[i] < key) swap(nums[i++], nums[++left]);
else if (nums[i] == key) i++;
else swap (nums[i], nums[--right]);
}
// 3. 分情况讨论
// [l, left] [left + 1, right - 1] [right, r]
// a:区间个数 b c
int c = r - right + 1, b = right - left - 1; // 原式: right - 1 - (left + 1) + 1
if (c >= k) return qsort(nums, right, r, k);
else if (b + c >= k) return key; // 直接就找到了
else return qsort(nums, l, left, k - b - c);
}
int GetRandom(vector<int>& nums, int left, int right)
{
return nums[rand() % (right - left) + left];
}
};
LCR 159. 库存管理 III(最小的k个数)
解析
题解
class Solution {
public:
vector<int> inventoryManagement(vector<int>& stock, int cnt) {
srand(time(NULL));
qsort(stock, 0, stock.size() - 1, cnt);
return {stock.begin(), stock.begin() + cnt};
}
void qsort(vector<int>& stock, int l, int r, int cnt)
{
// 1. 随机选择基准元素
int key = GetRandom(stock, l, r);
// 2. 根据基准元素将数组分三块
int i = l, left = l - 1, right = r + 1;
while (i < right)
{
if (stock[i] < key) swap(stock[i++], stock[++left]);
else if (stock[i] == key) i++;
else swap (stock[i], stock[--right]);
}
// 3. 分情况讨论
// [l, left] [left + 1, right - 1] [right, r]
// a:区间个数 b c
int a = left - l + 1, b = right - left - 1; // right - 1 - (left + 1) + 1
if (a > cnt) qsort(stock, l, left, cnt);
else if (a + b >= cnt) return;
else qsort(stock, right, r, cnt - a -b);
}
int GetRandom(vector<int>& stock, int left, int right)
{
return stock[rand() % (right - left + 1) + left];
}
};