Eclipse output is right while oj shows not right.


  • 0
    X

    test case:
    input: [1, 2], 1
    output: [2, 1]

    public class Rotate {

    public static void main(String[] args) {
    	// TODO Auto-generated method stub
    	int[] nums = {1, 2}; // nums could have single element
    	int k = 1; // k could be 0
    	rotate1(nums, k);
    }
    
    // solution 1
    public static void rotate1(int[] nums, int k) {
    	// deep copy of nums
    	k = k % nums.length; // 
    	int[] res = new int[nums.length];
    	if (k == 0) {
    		res = nums;
    	} else {
    		int offset = nums.length - k;
    		// 0 to k-1
    		for (int i = 0; i < k; i++) {
    			res[i] = nums[i + offset]; 
    		}
    		// k to nums.length-1
            for (int j = k; j < nums.length; j++) {
            	res[j] = nums[j - k];
            }
        }
        String str = Arrays.toString(res); // remember how to print array as string
        System.out.println(str);
    }
    

    }


Log in to reply
 

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