Can you find error?


  • 0
    K

    THis code is working , for every value i have tested but it is giving a wrong answer, when checked with an array of size 20000, and with k 11939 . Please, help me out.

    public:
        void rotate(vector<int>& nums, int k) {
            long long int i,j=0,temp=nums[0],temp2,start=nums[0];
            //cout<<nums[0];
            long long int n=nums.size();
            
            k=k%n;
            for(i=0;i<n;i++){
                if(j+k<n){
                    temp2=nums[j+k];
                    nums[j+k]=temp;
                    temp=temp2;
                    j+=k;
                }
                else{
                    temp2=nums[j+k-n];
                    nums[j+k-n]=temp;
                    if(start==temp2){
                        j+=k-n+1;
                        start=nums[j];
                        temp=nums[j];
                    }
                    else{
                        j+=k-n;
                        temp=temp2;
                    }
                }
            }
            //cout<<nums[11939];
        }
    };

  • 0

    @karan-vas1994 Don't you think the following is much simpler?

    class Solution {
    public:
        void rotate(vector<int>& nums, int k) 
        {
            if(nums.empty() || !k) return ;
            int size = nums.size();
            k %= size;
            reverse(nums.begin(), nums.end());
            reverse(nums.begin(), nums.begin()+k);
            reverse(nums.begin()+k, nums.end());
        }
    };
    
    

Log in to reply
 

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