What's wrong with my code? I don't get it! It's working in my local system


  • 0
    L

    public class Solution {
    public int[] rotate(int[] nums, int k) {

        	    if(k>=nums.length)
        	k= k%nums.length;
        int[] son = new int[nums.length];
        if(nums.length==1||k==0)
        	return nums;
        for (int j=k,i=0; j<nums.length;j++,i++){
        	
        	son[j]=nums[i];
        }
        for(int m = nums.length -k,j=0;m<nums.length;m++,j++){
        	son[j]=nums[m];
        }
        return son;
    }
    

    }


  • 1
    D

    One guess. Copy all the value in the array son back to the array nums.


  • 0
    L

    nothing changed


  • 0
    D

    According to the interface given by Leetcode, it is a function returns void. So it will check the array num for the correctness. So probably you need to modify your code to copy all the value in son back to nums.

    My modified version works:

    public void rotate(int[] nums, int k) {
    if(k>=nums.length)
    k= k%nums.length;
    int[] son = new int[nums.length];
    if(nums.length==1||k==0)
    return;
    for (int j=k,i=0; j<nums.length;j++,i++){

        son[j]=nums[i];
    }
    for(int m = nums.length -k,j=0;m<nums.length;m++,j++){
        son[j]=nums[m];
    }
    System.arraycopy(son, 0, nums, 0, son.length);
    

    }


  • 0
    L

    OH, That's why! Thanks!


Log in to reply
 

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