题意:

image.png

解题思路:

  1. 1. 第一种方法是,先将k后的数字放入临时数组,再将k前的数字追加,最后copy到原数组
  2. 2. 第二种方法是用递归,先整体翻转,再以k为中心,翻转2个局部

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer[] $nums
  4. * @param Integer $k
  5. * @return NULL
  6. */
  7. function rotate(&$nums, $k) {
  8. for ($i = 0; $i < count($nums); $i++) {
  9. $a[($i + $k) % count($nums)] = $nums[$i];
  10. }
  11. for ($i = 0; $i < count($nums); $i ++) {
  12. $nums[$i] = $a[$i];
  13. }
  14. return $nums;
  15. }
  16. function rotateByCopy(&$nums, $k) {
  17. $n = count($nums);
  18. $m = $k % $n; $i = 0;
  19. for ($j = $n - $m; $j < $n; $j++) $t[$i++] = $nums[$j];
  20. for ($j = 0; $j < $n - $m; $j ++) $t[$i++] = $nums[$j];
  21. for ($j = 0; $j < $n; $j++) $nums[$j] = $t[$j];
  22. }
  23. function rotateBySwap(&$nums, $k) {
  24. if ($nums == null || count($nums) == 0 || $k <= 0) return;
  25. $n = count($nums); $m = $k % $n;
  26. $this->reverse($nums, 0, $n - 1);
  27. $this->reverse($nums, 0, $m - 1);
  28. $this->reverse($nums, $m, $n - 1);
  29. }
  30. function reverse(&$nums, $i, $j) {
  31. for (; $i < $j; ++$i, --$j) {
  32. $tmp = $nums[$i];
  33. $nums[$i] = $nums[$j];
  34. $nums[$j] = $tmp;
  35. }
  36. }
  37. }

go代码实现:

  1. func rotate(nums []int, k int) {
  2. n := len(nums)
  3. m := k % n
  4. i := 0
  5. res := make([]int, len(nums))
  6. for j := n - m; j < n; j++ {
  7. res[i] = nums[j]
  8. i++
  9. }
  10. for j := 0; j < n - m; j++ {
  11. res[i] = nums[j]
  12. i++
  13. }
  14. for i, v := range res {
  15. nums[i] = v
  16. }
  17. }
  18. func rotateCopy(nums []int, k int) {
  19. k = len(nums) - k%len(nums)
  20. copy(nums, append(nums[k:], nums[0:k]...))
  21. }
  22. func reverse(nums []int) { // 翻转数组
  23. i,j := 0, len(nums)-1
  24. for i < j {
  25. nums[i],nums[j] = nums[j],nums[i]
  26. i++
  27. j--
  28. }
  29. }
  30. func rotateBySwap(nums []int, k int) {
  31. k = k % len(nums)
  32. reverse(nums[:len(nums)-k])
  33. reverse(nums[len(nums)-k:])
  34. reverse(nums)
  35. }