美文网首页
Wiggle Sort

Wiggle Sort

作者: BLUE_fdf9 | 来源:发表于2018-09-19 09:42 被阅读0次

题目
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....

答案

class Solution {
    // key: odd element needs to be greater than both sides while even elements need to be smaller than both sides
    // odd1 even1 odd2 even2 odd3 even3
    
    public void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
    
    public void wiggleSort(int[] nums) {
        for(int i = 0; i < nums.length; i+=2) {
            if(i > 0 && nums[i] > nums[i - 1]) swap(nums, i, i - 1);
            if(i < nums.length-1 && nums[i] > nums[i + 1]) swap(nums, i, i + 1);
        }
    }
}

相关文章

网友评论

      本文标题:Wiggle Sort

      本文链接:https://www.haomeiwen.com/subject/jbpbnftx.html