LintCode_508_Wiggle Sort

来源:互联网 发布:软件怎么控制license 编辑:程序博客网 时间:2024/05/20 05:45

Given an unsorted array nums, reorder it in-place such that

nums[0] <= nums[1] >= nums[2] <= nums[3]....
 注意事项

Please complete the problem in-place.

样例

Given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].

开始想将其排序后由后向前取一半的数倒序插入到前一半的数中 发现过于复杂 便尝试直接按要求操作

public class Solution {    /**     * @param nums a list of integer     * @return void     */    public void wiggleSort(int[] nums) {        // Write your code here        int n = nums.length;        int tmp = 0;        for(int i = 1 ; i < n ; i++){            if((i%2==1 && nums[i] < nums[i-1] ) || (i%2==0 && nums[i] > nums[i-1])){                tmp = nums[i];                nums[i] = nums[i-1];                nums[i-1] = tmp;            }        }    }}


0 0
原创粉丝点击