Leetcode: Rotate Array

我就是我 2022-08-05 15:21 33阅读 0赞

题目:

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

下面使用C#语言给出示例:
方法一:

  1. public void Rotate(int[] nums, int k)
  2. {
  3. int temp;
  4. int length = nums.Length;
  5. for (int i = 0; i < k; i++)
  6. {
  7. temp = nums[length - 1];
  8. for (int j = length - 1; j > 0; j--)
  9. {
  10. nums[j] = nums[j - 1];
  11. }
  12. nums[0] = temp;
  13. }
  14. }

但是这样提交以后系统提示超时,所以采用方法二。

方法二:
先翻转数组前n-k的部分,然后翻转数组后面k个数字,然后翻转整个数组。即:
[4,3,2,1,5,6,7],
[4,3,2,1,7,6,5],
[5,6,7,1,2,3,4].

  1. /* * 翻转数组nums中从begin到end的部分 */
  2. private void Reverse(int[] nums, int begin, int end)
  3. {
  4. int temp;
  5. for (int i = begin, j = end; i < j; i++, j--)
  6. {
  7. temp = nums[i];
  8. nums[i] = nums[j];
  9. nums[j] = temp;
  10. }
  11. }
  12. public void Rotate(int[] nums, int k)
  13. {
  14. int length = nums.Length;
  15. if (length <= 1)
  16. {
  17. return;
  18. }
  19. k %= length;// 处理k有肯定比length大的情况
  20. if (k <= 0)
  21. {
  22. return;
  23. }
  24. Reverse(nums, 0, length - k - 1);
  25. Reverse(nums, length - k, length - 1);
  26. Reverse(nums, 0, length - 1);
  27. }

发表评论

表情:
评论列表 (有 0 条评论,33人围观)

还没有评论,来说两句吧...

相关阅读