LeetCode Wiggle Sort II

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

Example 1:

Input: nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].

Example 2:

Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].

Note:
You may assume all input has valid answer.

Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?

 

这个题目,感觉好像很简单,就是把给定的数组进行排序,排序完成后,取一个最小元素然后再取一个最大元素好像就可以。但是经过测试用例的测试发现,有的数组包括很多大小重复的数字,这样的话,无论如何排序,始终有一个元素会出现等于的情况,就好比例子中的第二个,所以,排序好像是不行的。

最好的方法是将数组排序后分成两个数组,一个数组中装最大的数字partMax[],另外一个数组装最小的数字partMin[]。

nums = [1, 5, 1, 1, 6, 4]   partMax[]={4,5,6}    partMin[]={1,1,1}

然后将partMin[]数组中最右边的数字(也就是partMin[]数组中最大的数字)和partMax[]数组中最左边的数字(partMax[]中最小的数字)进行组合,组合到result数组中

第一次组合,result数组:[1,6]

如此进行循环:最终数组:[1,6,1,5,1,4]

 

//sort the array
Arrays.sort(nums);

// find mid point of array
int mid = (nums.length - 1 ) / 2;
int right = nums.length - 1;

//aux array to temp store the values
int[] result = new int[right + 1];
int counter = 0;

// select values from two parts of the array and arrange them in aux array
while(mid >= 0 || right > (nums.length - 1 ) / 2 ){

    if(counter % 2 == 0){
        result[counter] = nums[mid];
        mid--;
    } else {
        result[counter] = nums[right];
        right--;
    }

    counter++;
}

//now store back these values in input/original array
for(int i = 0; i < nums.length; i++){
    nums[i] = result[i];
}

 

 

 

你可能感兴趣的:(算法)