13、旋转数组
给定一个数组,将数组中的元素向右移k个位置,其中k是非负数,例如:
输入:[1,2,3,4,5,6]和k=3
输出:[5,6,1,2,3,4]
- slice
输入:[1,-100,78,90] k = 2
输出:[90,1,-100,78]
function rotate(key){
//参数处理,key>0
if(key<0||key === 0||key === this.length)return this;
if(key>this.length){key = key%this.length}
//slice支持负数索引,直接就是数组的后几位
return this.slice(-key).concat(this.slice(0,this.length-key))
}
Array.prototype.rotate = rotate;
let arr = [1,2,3,4,5,6,7],
k = 3;
arr.rotate(3); // [5, 6, 7, 1, 2, 3, 4]
slice
参数:开始点,结束点,返回:切割的数组
splice
参数:开始点、长度,返回:删除的这部分返回
- splice
输入:[1,-100,78,90] k = 2
输出:[90,1,-100,78]
function rotate(key){
//参数处理,key>0
if(key<0||key === 0||key === this.length)return this;
if(key>this.length){key = key%this.length}
return this.splice(this.length-key,key).concat(this)
}
Array.prototype.rotate = rotate;
let arr = [1,2,3,4,5,6,7],
k = 3;
arr.rotate(3); // [5, 6, 7, 1, 2, 3, 4]
- 最后一项删除放到最开头,执行k次
输入:[1,-100,78,90] k = 2
输出:[90,1,-100,78]
//写法一:
function rotate(key){
//参数处理,key>0
if(key<0||key === 0||key === this.length)return this;
if(key>this.length){key = key%this.length}
for(let i = 0;i<=key;i++){
this.unshift(this.pop()); //this.pop()最后一项;unshift首部插入
}
return this;
}
Array.prototype.rotate = rotate;
//写法二:
function rotate(key){
//参数处理,key>0
if(key<0||key === 0||key === this.length)return this;
if(key>this.length){key = key%this.length}
new Array(k).fill('').forEach((item)=>{
this.unshift(this.pop()); //this.pop()最后一项;unshift首部插入
})
return this;
}
Array.prototype.rotate = rotate;
let arr = [1,2,3,4,5,6,7],
k = 3;
arr.rotate(3); // [5, 6, 7, 1, 2, 3, 4]