LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
a(0) = nums[1]
a(1) = nums[3]
a(2) = nums[5]
a(3) = nums[0]
a(4) = nums[2]
a(5) = nums[4]

nums = 111465
a(i) = 145116
i    = 012345

目标情况:
nums = 161514
a(i) = 654111
i    = 012345
class Solution {
 public:
  void wiggleSort(vector<int>& nums) {
    if (empty(nums)) {
      return;
    }
    int sz = size(nums);
    nth_element(begin(nums), begin(nums) + sz / 2, end(nums));
    int m = nums[sz / 2];
#define a(i) nums[(2 * (i) + 1) % (sz | 1)]
    int i = 0;
    int j = 0;
    int k = sz - 1;
    while (j <= k) {
      if (a(j) > m) {
        swap(a(i), a(j));
        ++i;
        ++j;
      } else if (a(j) < m) {
        swap(a(j), a(k));
        --k;
      } else {
        ++j;
      }
    }
  }
};