题意:
解题思路:
1. 第一种方法是,先将k后的数字放入临时数组,再将k前的数字追加,最后copy到原数组
2. 第二种方法是用递归,先整体翻转,再以k为中心,翻转2个局部
PHP代码实现:
class Solution {
/**
* @param Integer[] $nums
* @param Integer $k
* @return NULL
*/
function rotate(&$nums, $k) {
for ($i = 0; $i < count($nums); $i++) {
$a[($i + $k) % count($nums)] = $nums[$i];
}
for ($i = 0; $i < count($nums); $i ++) {
$nums[$i] = $a[$i];
}
return $nums;
}
function rotateByCopy(&$nums, $k) {
$n = count($nums);
$m = $k % $n; $i = 0;
for ($j = $n - $m; $j < $n; $j++) $t[$i++] = $nums[$j];
for ($j = 0; $j < $n - $m; $j ++) $t[$i++] = $nums[$j];
for ($j = 0; $j < $n; $j++) $nums[$j] = $t[$j];
}
function rotateBySwap(&$nums, $k) {
if ($nums == null || count($nums) == 0 || $k <= 0) return;
$n = count($nums); $m = $k % $n;
$this->reverse($nums, 0, $n - 1);
$this->reverse($nums, 0, $m - 1);
$this->reverse($nums, $m, $n - 1);
}
function reverse(&$nums, $i, $j) {
for (; $i < $j; ++$i, --$j) {
$tmp = $nums[$i];
$nums[$i] = $nums[$j];
$nums[$j] = $tmp;
}
}
}
go代码实现:
func rotate(nums []int, k int) {
n := len(nums)
m := k % n
i := 0
res := make([]int, len(nums))
for j := n - m; j < n; j++ {
res[i] = nums[j]
i++
}
for j := 0; j < n - m; j++ {
res[i] = nums[j]
i++
}
for i, v := range res {
nums[i] = v
}
}
func rotateCopy(nums []int, k int) {
k = len(nums) - k%len(nums)
copy(nums, append(nums[k:], nums[0:k]...))
}
func reverse(nums []int) { // 翻转数组
i,j := 0, len(nums)-1
for i < j {
nums[i],nums[j] = nums[j],nums[i]
i++
j--
}
}
func rotateBySwap(nums []int, k int) {
k = k % len(nums)
reverse(nums[:len(nums)-k])
reverse(nums[len(nums)-k:])
reverse(nums)
}