Day1. Rotate Array(189)

问题描述
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
注意:k的值可能会大于n
思路1:先将整个数组逆序,然后分别对被分割开的两个部分做一次逆序

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
//
    function f(arr,n){
        arr.reverse();
        if(n!=1){
                var le = Math.ceil(n/2);
                for( var i = 0; i < le; i++){
                    var temp = arr[i];
                    arr[i] = arr[k-1-i];
                    arr[k-1-i] = temp;
                }
            }      
        var le = Math.floor((arr.length - n)/2)+n;
        var j=0;
        for( var i = n; i < le; i++){
            j++;
            var temp = arr[i];
            arr[i] = arr[arr.length - j];
            arr[arr.length - j] = temp;
        }                
    }
  
    if(k!==0 ){
       if(k

思路2:先在k的位置对数组进行切片,然后用数组拼接

var rotate = function(nums, k) {
    var le = nums.length;
    if(k!==0){
        if(k

文末彩蛋:
你真是小龙虾啊,又聋又瞎的


Day1. Rotate Array(189)_第1张图片
图片发自App

你可能感兴趣的:(Day1. Rotate Array(189))