I write my code in my computer and it is right but online judge thinks I am wrong?


  • 0
    A

    void rotate(int nums[], int n, int k) {
    int newnum[n];
    int i;
    for(i=0;i<n;i++)
    {
    newnum[i]=nums[i];
    }
    for(i=0;i<k;i++)
    {
    nums[i]=newnum[n-k+i];
    }
    int c=0;
    while(c<n-k)
    {
    nums[c+k]=newnum[c];
    c++;
    }

    }


  • 1
    C

    You haven't considered the case where k > n. Update k to shift only the effective offset as below.

    void rotate(int nums[], int n, int k) {
        int i;
        int newnum[n]; 
        for(i=0;i<n;i++) {
                newnum[i]=nums[i];
        }
        k= k%n ; // <--- Update K with effective shift 
        for(i=0;i<k;i++) {
                nums[i]=newnum[n-k+i];
        }
        int c=0;
        while(c<n-k) { nums[c+k]=newnum[c]; c++; }
    

    }


  • 0
    I

    +1 Here is my accepted solution:
    public static void rotate(int[] nums, int k) {
    if (nums == null || k == 0 || nums.length == 0 || nums.length == 1) {
    return;
    }

    	int[] newNums = new int[nums.length];
    	int startIndex = nums.length - (k % nums.length);
    	for (int i = 0; i < nums.length; i++) {
    		newNums[i] = nums[startIndex % nums.length];
    		++startIndex;
    	}
    
    	for (int c = 0; c < nums.length; c++) {
    		nums[c] = newNums[c];
    	}
    }

  • 0
    I

    I am learning the juggling algo now....so we do not have to create a new array...


Log in to reply
 

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