Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

旋转数组 #3

Open
JesseZhao1990 opened this issue May 2, 2018 · 8 comments
Open

旋转数组 #3

JesseZhao1990 opened this issue May 2, 2018 · 8 comments
Labels

Comments

@JesseZhao1990
Copy link
Owner

给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。

示例 1:

输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]

示例 2:

输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释: 
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]

说明:

尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的原地算法。

算法

方法1

var rotate = function(nums, k) {
    for(var i= 1; i<=k; i++){
        nums.unshift(nums.pop())
    }
};

方法2

var rotate = function(nums, k) {
    var a = nums.splice(-k,k);
    nums.unshift(...a);
};

方法3

var rotate = function(nums, k) {
    nums.splice(0,0,...nums.splice(-k,k))
};
@AshaLiu
Copy link

AshaLiu commented Aug 8, 2018

var rotate = function(list, k) {
    let array = list; // [1,2,3,4,5,6,7]
    let arrayLen = array.length; // 7
    let newArray = array.concat(array); // [1,2,3,4,5,6,7,1,2,3,4,5,6,7]
    let newArrayLen = newArray.length; // 14
    let num = k % arrayLen; // 3
    return newArray.slice(arrayLen-num, newArrayLen-num); //(4~11) [5,6,7,1,2,3,4]
};

@AshaLiu
Copy link

AshaLiu commented Aug 8, 2018

你的第一个是O(n)了吧

@383366204
Copy link

@AshaLiu 你这招首尾相连不错呀

@yunfour
Copy link

yunfour commented Aug 8, 2018

循环链表完美解决

@Kingsearch
Copy link

list.concat(list.splice(0, k))

@bjw1234
Copy link

bjw1234 commented Aug 18, 2018

arr.splice(-k).concat(arr);

这样可以吧?

@383366204
Copy link

arr.splice(-k).concat(arr);

这样可以吧?

你这样如果k大于数组长度呢

@bjw1234
Copy link

bjw1234 commented Jun 5, 2019

arr.splice(-k).concat(arr);

这样可以吧?

你这样如果k大于数组长度呢

var arr = [1,2,3,4,5,6,7];
var k = 10;
var val = k % arr.length;
arr.splice(-val).concat(arr);

那就对k的值取余,这样就可以了吧。:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

6 participants