Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
Step 1: [7,1,2,3,4,5,6]
Step 2: [6,7,1,2,3,4,5]
Step 3: [5,6,7,1,2,3,4]
My Solution:
var rotate = function(nums, k) {
while(k>0){
let lastelm = nums[nums.length-1];
for(let i =nums.length; i>0;i--){
temp = nums[i-1];
nums[i-1] = nums[i-2];
}
nums[0]=lastelm
k--;
}
};
I think my solution is O(k*nums.length)
I am modifying the entire array as many times as k
What could be a better approach to this?