[rotate array] why time limit exceeds?


  • 0
    K
    public class Solution {
        public void rotate(int[] nums, int k) {
            int temp;
            for(int i=0; i<k; i++)
            {
                temp = nums[nums.length-1];
                moveRightByOne(nums);
                nums[0] = temp;
            }
        }
        
        /* [1,2,3,4,5,6,7]
         * [1,1,2,3,4,5,6]
         */
        public void moveRightByOne(int[] nums)
        {
            int prev = nums[0];
            int temp = 0;
            for(int i=1; i<nums.length; i++)
            {
                temp = nums[i];
                nums[i] = prev;
                prev = temp;
            }
        }
    }

  • -1
    I
    public void rotate(int[] nums, int k) {
            if(k==1){
                return ;
            }
            for(int i=0;i<k;i++){
                moveToRight(nums);
            }
            
        }
        private void moveToRight(int[] nums){
            int last = nums[nums.length-1];
            for(int i=0;i<nums.length-1;i++){
                nums[i+1] = nums[i];
            }
            nums[0] = last;
        }

Log in to reply
 

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