쩨이엠 개발 블로그

[ Leetcode ] 324. Wiggle Sort II - Java 본문

개발/Programming

[ Leetcode ] 324. Wiggle Sort II - Java

쩨이엠 2021. 2. 8. 09:39
728x90
반응형

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

You may assume the input array always has a valid answer.

 

Example 1:

 
 Input: nums = [1,5,1,1,6,4] 
 Output: [1,6,1,5,1,4] 
 Explanation: [1,4,1,5,1,6] is also accepted.
 

Example 2:

 
 Input: nums = [1,3,2,2,3,1] 
 Output: [2,3,1,3,1,2]
 

 

Constraints:

  • 1 <= nums.length <= 5 * 104
  • 0 <= nums[i] <= 5000
  • It is guaranteed that there will be an answer for the given input nums.

 

 

Solution

 
 class Solution {
    public void wiggleSort(int[] nums) {
        Arrays.sort(nums);
        int[] answer = new int[nums.length];     
        int length = nums.length / 2;
        if(nums.length % 2 == 1){
            length = length+1;
        }
        for(int i=0; i< length; i++){
            answer[2*i] = nums[length-i-1];
        }
        for(int i=0; i< nums.length/2; i++){
            answer[2*i+1] = nums[nums.length-i-1];
        }
        for(int i=0; i< nums.length; i++){
            nums[i] = answer[i];
        }
    } 
 }
 

1. sort

2. 반으로 나눠서 짝수는 제일 큰수부터 / 홀수는 배열의 반부터

3. 배열의 갯수가 홀수인 경우는 홀수 길이를 1 더해준다

 

728x90
반응형
Comments