Last updated on October 5th, 2024 at 09:27 pm
Here, We see Wiggle Sort II LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Sort
Companies
Level of Question
Medium
Wiggle Sort II LeetCode Solution
Table of Contents
Problem Statement
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]
1. Wiggle Sort II Leetcode Solution C++
class Solution { public: void wiggleSort(vector<int>& nums) { vector<int> sorted(nums); sort(sorted.begin(), sorted.end()); for (int i=nums.size()-1, j=0, k=i/2+1; i>=0; i--) nums[i] = sorted[i&1 ? k++ : j++]; } };
2. Wiggle Sort II Solution Java
class Solution { public void wiggleSort(int[] nums) { int n=nums.length-1; int[] newarr=Arrays.copyOf(nums,nums.length); Arrays.sort(newarr); for(int i=1;i<nums.length;i+=2) nums[i]=newarr[n--]; for(int i=0;i<nums.length;i+=2) nums[i]=newarr[n--]; } }
3. Wiggle Sort II Solution JavaScript
var wiggleSort = function(nums) { nums.sort((b,a)=>b-a); let mid = Math.floor(nums.length/2) mid+=nums.length%2==0?0:1; let even = nums.slice(0, mid); let odd = nums.slice(mid); for(let i=0;i<nums.length;i++) { if (i%2==0) { nums[i] = even.pop(); } else { nums[i] = odd.pop(); } } };
4. Wiggle Sort II Solution Python
class Solution(object): def wiggleSort(self, nums): nums.sort() half = len(nums[::2]) nums[::2], nums[1::2] = nums[:half][::-1], nums[half:][::-1]