JAVA O(n) solution


  • 0
    H

    Keep swaping with next integer once the condition doesn't meet

    public class Solution {
        public void wiggleSort(int[] nums) {
            if (nums == null || nums.length == 0) return;
            boolean isEven = true;
            for (int i = 0; i < nums.length - 1; i++) {
                if ((isEven && nums[i] > nums[i + 1]) || (!isEven && nums[i] < nums[i + 1])) {
                    swap(nums, i, i + 1);
                }
                isEven = !isEven;
            }
        }
    
        public void swap(int[] nums, int i, int j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.