Tuesday, November 17, 2015

[leetcode]Wiggle Sort

利用好传递性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class Solution {
    public void wiggleSort(int[] nums) {
        boolean large = true;
        for (int i = 1; i < nums.length; i++){
         if ((large && nums[i-1] > nums[i])||(!large && nums[i-1] < nums[i])){
          swap(nums, i-1, i);
         }
         large = !large;
        }
    }

    public void swap(int []array, int index1, int index2){
     int temp = array[index1];
     array[index1] = array[index2];
     array[index2] = temp;
    }
}

No comments:

Post a Comment