Given an unsorted array nums
, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]...
.
For example, given nums = [3, 5, 2, 1, 6, 4]
, one possible answer is [1, 6, 2, 5, 3, 4]
.
此题需要把数组序号分成偶数和奇数来区别对待,代码如下:
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545 }
public class Solution {
public void wiggleSort(int[] nums) {
for(int i=0;i<nums.length-1;i++){
if(i%2==0){
if(nums[i]>nums[i+1]) swap(nums,i,i+1);
}else{
if(nums[i]<nums[i+1]) swap(nums,i,i+1);
}
}
}
public void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
时间: 2024-10-06 13:39:58