324. 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?

這道題,我開始就想,很簡單啊,先把nums排序,小的數放在偶數位,大的數放在奇數位,這樣就ok了。

class Solution {
    public void wiggleSort(int[] nums) {
        Arrays.sort(nums);
		int n = nums.length;
		int[] arr = new int[n];
		int j = 0;
		int count = 0; 
		for(int i = 0; j < n ; i++) {  //先把最小的幾個數放在奇數位上
			arr[j] = nums[i];
			j += 2;
			count++;
		}
		
		for(int i = 1 ; count < n    ; i += 2) {   //把剩下排好序的大數放在剩下的偶數位上
			arr[i] = nums[count];
            count++;
		}


		for(int i = 0 ; i < n ; i++) {
			nums[i] = arr[i];
		}
    }
}

但是,我提交後,發現自己錯了,Wrong Answer
錯誤的案例是:[4,5,5,6]
這時候,我才發現了自己沒有考慮重疊元素。看了discuss,有個人總結的很多,但是我就是看不懂啊,後來在百度搜了搜,發現了一個人的答案,他的思路和我之前的一樣,但是我運行他的答案,竟然對了!
仔細一看,發現了我與人家的區別,他是採用倒敘的方式,先把大的數放在奇數位,然後把小的數放在偶數位,(而我是先把小的數放在偶數位,在把大的數放在奇數位),不過我感覺這位應該對的也是湊巧,因爲他說也可以先放小的,但是我先放小的就錯了。。。

正確的答案:

class Solution {
    public void wiggleSort(int[] nums) {
        Arrays.sort(nums);
        int[] arr = new int[nums.length];
        int i = 1,j=0,k=nums.length-1;
        while(i<arr.length){
            arr[i]=nums[k--];
            i+=2;
        }
        while(j<arr.length){
            arr[j] = nums[k--];
            j+=2;
        }
        for(int x=0;x<nums.length;x++){
            nums[x] = arr[x];
        }
    }
}

答案來自:324. Wiggle Sort II

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章