Description:
Given an array, rotate the array to the right by_k_steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and _k_ = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and _k_ = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
思路:题目要求将数组旋转 k 次。可以先创建一个新数组,然后将原数组中的后 k 个元素放到新数组的前 k 个位置,将原数组中的前 n-k 个元素放到新数组的后 n-k 个位置,然后将新数组的元素复制到旧数组中,最后删除新数组。
注意:c++ 中 memcpy 函数用法
函数原型: void *memcpy(void*dest, const void *src, size_t n);
功能:由src指向地址为起始地址的连续n个字节的数据复制到以destin指向地址为起始地址的空间内。
C++ 代码
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n=nums.size();
k=k%n;
int* temp=new int[n];
memcpy(temp,&nums[0]+(n-k),sizeof(int)*k);
memcpy(temp+k,&nums[0],sizeof(int)*(n-k));
memcpy(&nums[0],temp,sizeof(int)*n);
delete[] temp;
}
};
运行时间:16ms
运行内存:
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于