欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > C++ | Leetcode C++题解之第324题摆动排序II

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

2024/11/30 12:48:16 来源:https://blog.csdn.net/Ddddddd_158/article/details/140942770  浏览:    关键词:C++ | Leetcode C++题解之第324题摆动排序II

题目:

题解:

class Solution {
public:int partitionAroundPivot(int left, int right, int pivot, vector<int> &nums) {int pivotValue = nums[pivot];int newPivot = left;swap(nums[pivot], nums[right]);for (int i = left; i < right; ++i) {if (nums[i] > pivotValue) {swap(nums[i], nums[newPivot++]);}}swap(nums[right], nums[newPivot]);return newPivot;}int findKthLargest(vector<int> &nums, int k) {int left = 0, right = nums.size() - 1;default_random_engine gen((random_device())());while (left <= right) {uniform_int_distribution<int> dis(left, right);int pivot = dis(gen);int newPivot = partitionAroundPivot(left, right, pivot, nums);if (newPivot == k - 1) {return nums[newPivot];} else if (newPivot > k - 1) {right = newPivot - 1;} else { left = newPivot + 1;}}return nums[k - 1];}inline int transAddress(int i, int n) {return (2 * n - 2 * i - 1) % (n | 1);}void wiggleSort(vector<int>& nums) {int n = nums.size();int x = (n + 1) / 2;int mid = x - 1;int target = findKthLargest(nums, n - mid);for (int k = 0, i = 0, j = n - 1; k <= j; k++) {if (nums[transAddress(k, n)] > target) {while (j > k && nums[transAddress(j, n)] > target) {j--;}swap(nums[transAddress(k, n)], nums[transAddress(j--, n)]);}if (nums[transAddress(k, n)] < target) {swap(nums[transAddress(k, n)], nums[transAddress(i++, n)]);}}}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com