当前位置:   article > 正文

C++ | Leetcode C++题解之第324题摆动排序II

C++ | Leetcode C++题解之第324题摆动排序II

题目:

题解:

  1. class Solution {
  2. public:
  3. int partitionAroundPivot(int left, int right, int pivot, vector<int> &nums) {
  4. int pivotValue = nums[pivot];
  5. int newPivot = left;
  6. swap(nums[pivot], nums[right]);
  7. for (int i = left; i < right; ++i) {
  8. if (nums[i] > pivotValue) {
  9. swap(nums[i], nums[newPivot++]);
  10. }
  11. }
  12. swap(nums[right], nums[newPivot]);
  13. return newPivot;
  14. }
  15. int findKthLargest(vector<int> &nums, int k) {
  16. int left = 0, right = nums.size() - 1;
  17. default_random_engine gen((random_device())());
  18. while (left <= right) {
  19. uniform_int_distribution<int> dis(left, right);
  20. int pivot = dis(gen);
  21. int newPivot = partitionAroundPivot(left, right, pivot, nums);
  22. if (newPivot == k - 1) {
  23. return nums[newPivot];
  24. } else if (newPivot > k - 1) {
  25. right = newPivot - 1;
  26. } else {
  27. left = newPivot + 1;
  28. }
  29. }
  30. return nums[k - 1];
  31. }
  32. inline int transAddress(int i, int n) {
  33. return (2 * n - 2 * i - 1) % (n | 1);
  34. }
  35. void wiggleSort(vector<int>& nums) {
  36. int n = nums.size();
  37. int x = (n + 1) / 2;
  38. int mid = x - 1;
  39. int target = findKthLargest(nums, n - mid);
  40. for (int k = 0, i = 0, j = n - 1; k <= j; k++) {
  41. if (nums[transAddress(k, n)] > target) {
  42. while (j > k && nums[transAddress(j, n)] > target) {
  43. j--;
  44. }
  45. swap(nums[transAddress(k, n)], nums[transAddress(j--, n)]);
  46. }
  47. if (nums[transAddress(k, n)] < target) {
  48. swap(nums[transAddress(k, n)], nums[transAddress(i++, n)]);
  49. }
  50. }
  51. }
  52. };
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/946436
推荐阅读
相关标签
  

闽ICP备14008679号