给出一个整数数组,输出最小的k个数。

  • 采用快速选择算法

https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/

  1. class Solution {
  2. int partition(vector<int>& nums, int l, int r) {
  3. int pivot = nums[r];
  4. int i = l - 1;
  5. for (int j = l; j <= r - 1; ++j) {
  6. //从l到r-1遍历数组,发现小于pivot的数,放到左边
  7. if (nums[j] <= pivot) {
  8. //待交换位置向前移动
  9. i = i + 1;
  10. swap(nums[i], nums[j]);
  11. }
  12. }
  13. //将pivot放在他该放的位置
  14. swap(nums[i + 1], nums[r]);
  15. //返回排序好的位置
  16. return i + 1;
  17. }
  18. // 基于随机的划分
  19. int randomized_partition(vector<int>& nums, int l, int r) {
  20. //生成[l,r]之间的随机数
  21. int i = rand() % (r - l + 1) + l;
  22. //将l和r交换位置
  23. //方便函数的编写,每次默认pivot是r
  24. swap(nums[r], nums[i]);
  25. return partition(nums, l, r);
  26. }
  27. void randomized_selected(vector<int>& arr, int l, int r, int k) {
  28. if (l >= r) return;
  29. //划分之后只能得到是第k小的数,但数据并非有序
  30. int pos = randomized_partition(arr, l, r);
  31. //当前区域内有多少个数
  32. int num = pos - l + 1;
  33. if (k == num) return;
  34. else if (k < num) randomized_selected(arr, l, pos - 1, k);
  35. else randomized_selected(arr, pos + 1, r, k - num);
  36. }
  37. public:
  38. vector<int> getLeastNumbers(vector<int>& arr, int k) {
  39. //初始化seed函数
  40. srand((unsigned)time(NULL));
  41. randomized_selected(arr, 0, (int)arr.size() - 1, k);
  42. vector<int>vec;
  43. for (int i = 0; i < k; ++i) vec.push_back(arr[i]);
  44. return vec;
  45. }
  46. };

水壶问题

  1. using PII = pair<int, int>;
  2. class Solution {
  3. public:
  4. bool canMeasureWater(int x, int y, int z) {
  5. stack<PII> stk;
  6. //和push类似,更高效
  7. stk.emplace(0, 0);
  8. //定义hash函数,将pair的first和second进行异或
  9. auto hash_function = [](const PII& o) {return hash<int>()(o.first) ^ hash<int>()(o.second);};
  10. //将pair和hash值进行关联
  11. unordered_set<PII, decltype(hash_function)> seen(0, hash_function);
  12. while (!stk.empty()) {
  13. //判断stk中是否已经有元素
  14. if (seen.count(stk.top())) {
  15. stk.pop();
  16. continue;
  17. }
  18. seen.emplace(stk.top());
  19. //将remain取出来
  20. auto [remain_x, remain_y] = stk.top();
  21. stk.pop();
  22. if (remain_x == z || remain_y == z || remain_x + remain_y == z) {
  23. return true;
  24. }
  25. // 把 X 壶灌满。
  26. stk.emplace(x, remain_y);
  27. // 把 Y 壶灌满。
  28. stk.emplace(remain_x, y);
  29. // 把 X 壶倒空。
  30. stk.emplace(0, remain_y);
  31. // 把 Y 壶倒空。
  32. stk.emplace(remain_x, 0);
  33. // 把 X 壶的水灌进 Y 壶,直至灌满或倒空。
  34. stk.emplace(remain_x - min(remain_x, y - remain_y), remain_y + min(remain_x, y - remain_y));
  35. // 把 Y 壶的水灌进 X 壶,直至灌满或倒空。
  36. stk.emplace(remain_x + min(remain_y, x - remain_x), remain_y - min(remain_y, x - remain_x));
  37. }
  38. return false;
  39. }
  40. };
  41. 作者:LeetCode-Solution
  42. 链接:https://leetcode-cn.com/problems/water-and-jug-problem/solution/shui-hu-wen-ti-by-leetcode-solution/
  43. 来源:力扣(LeetCode
  44. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。