280. Wiggle Sort

https://leetcode.com/problems/wiggle-sort/description/

The main idea of ​​the title: a series of irregular numbers should be arranged in a hump shape, that is, a[1] , a[3], a[5] are larger than the numbers on the left and right sides (>=).
Question idea 1: Sort first, Then insert a new array, time complexity:
O(nlgn)+O(n)=O(nlgn), space O(n).

Topic idea 2: One traversal, a[i] is compared with a[i-1], when i is odd, a[i] should be greater than a[i-1], otherwise the two elements are exchanged. When i is even, a[i] should be less than a[i-1], otherwise swap. One pass can ensure that the odd position element is larger than both sides.

Code 1:

class Solution {
public:
    void wiggleSort(vector<int>& nums) {
        int n = nums.size();
        sort(nums.begin(), nums.end());
        vector<int> res(n);  //辅助数组
        int i;
        for (i = 0; i < n/2; i++) {
            res[2*i] = nums[i];
            res[2*i+1] = nums[n-1-i];  //"驼峰"位置
        }
        if (n % 2 == 1) res[2*i] = nums[i];  //特殊处理
        nums = res;
    }
};

Code 2:

class Solution {
public:
    void wiggleSort(vector<int>& nums) {
        int n = nums.size();
        for (int i = 1; i < n; i++) {
            if (i%2 && nums[i-1] > nums[i] || !(i%2) && nums[i-1] < nums[i]) {  //注意&&优先级大于||
                swap(nums[i-1], nums[i]);
            }
        }
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325698686&siteId=291194637