Java


  • 0
    J
    public void wiggleSort(int[] nums) {
            boolean isUp = true;
            for (int i = 0; i < nums.length-1; i++) {
                if (isUp) {
                    if (nums[i] > nums[i+1]) {
                        int temp = findTheNextIndex(nums, i, true);
                        swap(nums, i+1, temp);
                    }
                } else {
                    if (nums[i] < nums[i + 1]) {
                        int temp = findTheNextIndex(nums, i, false);
                        swap(nums, i+1, temp);
                    }
                }
                isUp = !isUp;
            }
        }
    
        private void swap(int[] nums, int i, int j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    
        private int findTheNextIndex(int[] nums, int index, boolean isHigher) {
            int target = nums[index];
            for (int i=index+1; i<nums.length; i++) {
                if (isHigher) {
                    if (nums[i] > target) {
                        return i;
                    }
                } else {
                    if (nums[i] < target) {
                        return i;
                    }
                }
            }
            // can't find what you are looking for.
            return index;
        }

Log in to reply
 

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