LeetCode Rotate Array
来源:互联网 发布:中科院院士 知乎 编辑:程序博客网 时间:2024/05/16 17:25
LeetCode Rotate Array
Rotate Array Total Accepted: 5488 Total Submissions: 29811 My Submissions Question Solution
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.
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.
题目意思就是将数组按照指定的位置进行旋转,其中的Note说明至少有三种方法。
方法一:采用一个辅助空间,然后进行数据的拷贝,在此使用memcpy和memset等(面试有一些关于memcpy和memmove的题目,可以自行google),空间复杂度O(n)
void rotate(int nums[], int n, int k) {if (n <= 0 || k == 0)return;k > n ? k = k%n : n;const int intSize = sizeof(int);int * arr = new int[n];memset(arr, 0, n*intSize);memcpy(arr, nums, n*intSize);memcpy(nums, arr + (n-k), k*intSize);memcpy(nums + k, arr, (n - k)*intSize);delete[] arr;}
方法二:每个数字移动k次,空间复杂度O(1),时间复杂度O(K*N)
for (int i = 0; i < k; i++)//每个数字移动k次{int tmp = nums[n - 1];for (int j = n - 1; j >= 0; j--)//后移数组元素{nums[j] = nums[j - 1];}nums[0] = tmp;}
方法三:根据规律旋转,时间复杂度和系统函数有关,空间复杂度O(0)
void rotate(int nums[], int n, int k) {reverse(nums, nums + n);//翻转整个数组[7,6,5,4,3,2,1]reverse(nums, nums + k%n);//翻转从起始位置到k%n位置处[5,6,7,4,3,2,1]reverse(nums + k%n, nums + n);//翻转剩余部分[5,6,7,1,2,3,4]}
0 0
- [leetcode][array] Rotate Array
- LeetCode[Array]: Rotate Image
- LeetCode:Rotate Array
- [LeetCode] Rotate Array
- *LeetCode-Rotate Array
- [LeetCode]189.Rotate Array
- Rotate Array - LeetCode - Java
- Rotate Array--Leetcode(Java)
- Leetcode--Rotate Array
- LeetCode: Rotate Array
- LeetCode Rotate Array
- Rotate Array(leetcode)
- leetcode Rotate Array
- Leetcode: Rotate Array
- [Leetcode]11 Rotate Array
- [LeetCode][189][Rotate Array]
- Leetcode:Rotate Array
- LeetCode: Rotate Array
- Hibernate 使用 HQL 查询 使用List 作为查询条件的注意(也是相当于别名查询)
- poj3268 dijsktra
- C语言宏定义技巧(常用宏定义)
- 单个按钮同时选择多个文件上传
- 欢迎使用CSDN-markdown编辑器
- LeetCode Rotate Array
- android VelocityTracker简单用法
- ARM 设备树-device tree
- c++ new 重载的几种形式
- Ubuntu常用快捷键
- namespace使用总结
- 黑马程序员——Java基础语法
- Linux中断(interrupt)子系统之二:arch相关的硬件封装层
- 黑马程序员--Java基础--java基础常识