ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
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:** rotate 1 steps to the right: `[7,1,2,3,4,5,6]` rotate 2 steps to the right: `[6,7,1,2,3,4,5]` rotate 3 steps to the right: `[5,6,7,1,2,3,4]` **Example 2:** **Input:** `[-1,-100,3,99]` and *k* = 2 **Output:** \[3,99,-1,-100\] **Explanation:** rotate 1 steps to the right: \[99,-1,-100,3\] rotate 2 steps to the right: \[3,99,-1,-100\] ``` var rotate = function(nums, k) { var le = nums.length; if(k!==0){ if(k<le){ var arr = nums.splice(0,le-k) for(var i=0; i<le-k; i++){ nums.push(arr[i]); } } else{ k = k % nums.length; if(k!==0){ var arr = nums.splice(0,nums.length-k); for(var i=0; i<le-k; i++){ nums.push(arr[i]); } } } } }; ``` ``` var rotate = function(nums, k) {   k %= nums.length; var tmp = \[\]; if (k){tmp = nums.slice(-k);}   nums.splice(-k, k); Array.prototype.unshift.apply(nums, tmp); }; ```