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

旋转数组算法题 #32

Open
hanyueqiang opened this issue Dec 18, 2020 · 0 comments
Open

旋转数组算法题 #32

hanyueqiang opened this issue Dec 18, 2020 · 0 comments

Comments

@hanyueqiang
Copy link
Owner

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

输入: [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]

解析:
1。使用slice截取元素,再进行拼接

function roate1(arr, num) {
   return arr.slice(-num).concat(arr.slice(0,arr.length-num))
 }

2.利用数组的pop unshift

function rotate(arr, num) {
      // num超出数组长度返回原数组
      if(num >= arr.length) {
        return arr
      }
      for(let n=1; n<=num; n++) {
        arr.unshift(arr.pop());
      }
      return arr
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant