标签:space oid swa -- 避免 with media find define
class Solution {
public:
void wiggleSort(vector<int>& nums) {
int n = nums.size();
// Find a median.
auto midptr = nums.begin() + n / 2;
nth_element(nums.begin(), midptr, nums.end());
//求第n/2小的数放在n/2位置上
//最快达到O(n)
int mid = *midptr;
// Index-rewiring.
#define A(i) nums[(1+2*(i)) % (n|1)]
//避免0和越界
// 3-way-partition-to-wiggly in O(n) time with O(1) space.
int i = 0, j = 0, k = n - 1;
//保证逻辑上的A(i)是这样的
//过了mid后保证,有大的换到前面去
while (j <= k) {
if (A(j) > mid)
swap(A(i++), A(j++));
else if (A(j) < mid)
swap(A(j), A(k--));
else
j++;
}
}
};
一道O(n)+S(1)的leetcode题大神stephan的简要解析
标签:space oid swa -- 避免 with media find define
原文地址:http://www.cnblogs.com/fenglongyu/p/7640607.html