给出一个整数数组,输出最小的k个数。
https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/
class Solution {
int partition(vector<int>& nums, int l, int r) {
int pivot = nums[r];
int i = l - 1;
for (int j = l; j <= r - 1; ++j) {
//从l到r-1遍历数组,发现小于pivot的数,放到左边
if (nums[j] <= pivot) {
//待交换位置向前移动
i = i + 1;
swap(nums[i], nums[j]);
}
}
//将pivot放在他该放的位置
swap(nums[i + 1], nums[r]);
//返回排序好的位置
return i + 1;
}
// 基于随机的划分
int randomized_partition(vector<int>& nums, int l, int r) {
//生成[l,r]之间的随机数
int i = rand() % (r - l + 1) + l;
//将l和r交换位置
//方便函数的编写,每次默认pivot是r
swap(nums[r], nums[i]);
return partition(nums, l, r);
}
void randomized_selected(vector<int>& arr, int l, int r, int k) {
if (l >= r) return;
//划分之后只能得到是第k小的数,但数据并非有序
int pos = randomized_partition(arr, l, r);
//当前区域内有多少个数
int num = pos - l + 1;
if (k == num) return;
else if (k < num) randomized_selected(arr, l, pos - 1, k);
else randomized_selected(arr, pos + 1, r, k - num);
}
public:
vector<int> getLeastNumbers(vector<int>& arr, int k) {
//初始化seed函数
srand((unsigned)time(NULL));
randomized_selected(arr, 0, (int)arr.size() - 1, k);
vector<int>vec;
for (int i = 0; i < k; ++i) vec.push_back(arr[i]);
return vec;
}
};
水壶问题
using PII = pair<int, int>;
class Solution {
public:
bool canMeasureWater(int x, int y, int z) {
stack<PII> stk;
//和push类似,更高效
stk.emplace(0, 0);
//定义hash函数,将pair的first和second进行异或
auto hash_function = [](const PII& o) {return hash<int>()(o.first) ^ hash<int>()(o.second);};
//将pair和hash值进行关联
unordered_set<PII, decltype(hash_function)> seen(0, hash_function);
while (!stk.empty()) {
//判断stk中是否已经有元素
if (seen.count(stk.top())) {
stk.pop();
continue;
}
seen.emplace(stk.top());
//将remain取出来
auto [remain_x, remain_y] = stk.top();
stk.pop();
if (remain_x == z || remain_y == z || remain_x + remain_y == z) {
return true;
}
// 把 X 壶灌满。
stk.emplace(x, remain_y);
// 把 Y 壶灌满。
stk.emplace(remain_x, y);
// 把 X 壶倒空。
stk.emplace(0, remain_y);
// 把 Y 壶倒空。
stk.emplace(remain_x, 0);
// 把 X 壶的水灌进 Y 壶,直至灌满或倒空。
stk.emplace(remain_x - min(remain_x, y - remain_y), remain_y + min(remain_x, y - remain_y));
// 把 Y 壶的水灌进 X 壶,直至灌满或倒空。
stk.emplace(remain_x + min(remain_y, x - remain_x), remain_y - min(remain_y, x - remain_x));
}
return false;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/water-and-jug-problem/solution/shui-hu-wen-ti-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。