2015年11月5日星期四

Leetcode 280 Wiggle Sort

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].
Solution 1: simple iterate.
 public class Solution {  
   public void wiggleSort(int[] nums) {  
     int n=nums.length;  
     for (int i=0; i<n; i+=2) {  
       if (i+1<n && nums[i]>nums[i+1]) swap(nums,i,i+1);  
       if (i+2<n && nums[i+1]<nums[i+2]) swap(nums,i+1,i+2);  
     }  
   }  
   private void swap(int[] nums, int i, int j) {  
     int temp=nums[i];  
     nums[i]=nums[j];  
     nums[j]=temp;  
   }  
 }  

没有评论:

发表评论