Stuck on test case [4,5,5,6]. Need Help.


  • 0
    K

    I used the following approach.

    void wiggleSort(int *a,int n)
    {

    int i,j,tmp,k;
    if(n<=1)
    return;
    else
    {
    
        qsort(a,n,sizeof(int),cmp);  //sort the array
        if(n==2)
        return;
        else
        {
             for(j=n/2,k=n-1;j<=k;j++,k--)  //swap the array from n/2 to n
             {
                 tmp=a[j];
                 a[j]=a[k];
                 a[k]=tmp;
             }
            j=n/2;
            for(i=1;i<n;i=i+2)      // swap a[i] with a[j] and increament i by i=i+2 and j=j+1
            {
                if(j<n)
                {
                    tmp=a[i];
                    a[i]=a[j];
                    a[j]=tmp;
                    j=j+1;
                }
                if(j>=n)
                break;
            }
        }
    }}

  • 0
    K

    Is my approach is correct? If yes then what did i missed. Please help


  • 0

    the right answer should be 5-6-4-5.

    I have to say I think your ideas is not suitable for the problem.

    What you do is sort the array , This is OK

    Next, you swap the array from the n/2 to the n . Why ? This just make your sorting messy. This will
    crash your order information

    so, I do think you have not understand the problem. I recommend you to read my solution or the top voted solution.

    https://leetcode.com/discuss/80100/recommend-beginners-implementation-explanation-referenced


  • 0
    K

    I swap the array from n/2 to n for remove the conflict generate by equal elements. for example : for test case [1,3,2,2,3,1] if i do not swap then answer will be [1,2,2,3,1,3] which is wrong. But if i swap , the answer will be [1,3,2,3,1,2] which is correct.


  • 0
    B

    have you found out how pass this test case?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.