LeetCode刷题实战280:摆动排序
程序IT圈
共 2224字,需浏览 5分钟
·
2021-06-02 20:40
Given an unsorted array nums, reorder it
in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
示例
输入: nums = [3,5,2,1,6,4]
输出: 一个可能的解答是 [3,5,1,6,2,4]
解题
public class Solution {
public void wiggleSort(int[] nums) {
if (nums == null || nums.length < 2) return;
for (int i = 1; i < nums.length; i++) {
if ((i % 2 == 0 && nums[i] > nums[i - 1]) || (i % 2 == 1 && nums[i] < nums[i - 1])) {
int tmp = nums[i];
nums[i] = nums[i - 1];
nums[i - 1] = tmp;
}
}
}
}
评论