Thinking process

If I sort it, can I get some pattern?

  • move the largest one forward
  • n log n

What if I don't sort?

  • thinking about this case 3 5 6
  • since 3 is smaller than 5, if 6 is bigger than 5, then swap 5 and 6, => 3 6 5
  • this will not affect the numbers before
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 - 1] <= nums[i]) || (i % 2 == 0 && nums[i - 1] >= nums[i])) continue;

            int tmp = nums[i];
            nums[i] = nums[i - 1];
            nums[i - 1] = tmp;
        }
    }
}

results matching ""

    No results matching ""