public class Solution {
public void wiggleSort(int[] nums) {
for(int i=0;i<nums.length;i++)
if(i%2==1){
if(nums[i1]>nums[i]) swap(nums, i);
}else if(i!=0 && nums[i1]<nums[i]) swap(nums, i);
}
public void swap(int[] nums, int i){
int tmp=nums[i];
nums[i]=nums[i1];
nums[i1]=tmp;
}
}
Java O(N) solution




@rajdev Not sure what you mean. It's just a normal comparison. It's maybe unusual to compare booleans, but nothing special that needs extra explanation.

Maybe
for (int i=1; i<nums.length; i++) { int previous = nums[i1]; if ((nums[i] > previous) != (i%2 == 1)) { nums[i1] = nums[i]; nums[i] = previous; } }
would be clearer? We want a number to be larger than the previous (
nums[i] > previous
) if and only if it's at an odd index (i%2 == 1
). With==
it's effectively "if and only if", but I want to swap when that's violated, so I negate to!=
here. Maybeif (! ((nums[i] > prev) == (i%2 == 1))) {
would be clearer to some, but I don't like the extra parentheses and operator.

Hi @StefanPochmann, could you please let me know how long it takes for you to come up with a solution like this? I've been wondering these days :P

Can someone explain why the same logic of mine fails:
public class Solution { public void wiggleSort(int[] nums) { for(int i=0;i<nums.length;i++) if(i%2==1 &&(nums[i1]>nums[i])){ // I have combined here thats why it fails swap(nums, i); }else if(i!=0 && nums[i1]<nums[i]) swap(nums, i); } void swap ( int [] nums, int i) { int temp=nums[i]; nums[i]=nums[i1]; nums[i1]=temp; } }

@StefanPochmann Could you explain the difference of using == and && ? Still don't understand "if and only if". Thank you so much