Easy to understand but not the best Java solution

  • 0
        I recently read the CTCI book and this is much like question 1.8 of the Array & String chapter. 
        After several tests on some extreme test cases, the codes below is accepted.  
        The basic idea is to concatenate[1,2,3,4,5,6,7] to [1,2,3,4,5,6,7,1,2,3,4,5,6,7] 
        and extract the sub array as required.
                public class Solution {
                        public void rotate(int[] nums, int k) {
                            if(nums == null || nums.length == 0) return;
                            int len = nums.length;
                            while( k > len){
                                k -= len;
                            int[] temp = new int[len + len];
                            System.arraycopy(nums, 0, temp, 0, len);
                            System.arraycopy(nums, 0, temp, len, len);
                            for(int i = 0; i < len; i++){
                                nums[i] = temp[i + len - k];

Log in to reply

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