无意间看到,力扣存算法代码居然还得升级vip。。。好吧,我自己存吧
其他的题找不回来了......重写吧
golang:
Go
func rotate(nums []int, k int) {
// 第一想到的
// n := len(nums)
// k %= n
// newNums := nums[n-k:]
// numsFeature := append(newNums, nums[:n-k]...)
// for i, num := range numsFeature {
// nums[i] = num
// }
//优化后的,性能更好
n := len(nums)
k %= n
newNums := append(nums[n-k:], nums[:n-k]...)
for i := 0; i < len(nums); i++ {
nums[i] = newNums[i]
}
}
javascript:
javascript
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
let n = nums.length;
let ks = k % n;
let newNumber = nums.slice(n-ks)
let footNumber = nums.slice(0,n-ks)
let newFeature = newNumber.concat(footNumber)
for(let i=0;i<n;i++){
nums[i] = newFeature[i]
}
};
python:
python
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k % n
if k == 0 or n <= 1:
return # 如果 k 为 0 或数组长度小于等于 1,不需要旋转
nums[:] = nums[-k:] + nums[:-k]
记录一下,以便后面回来coding~