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.
[show hint]
Credits: Special thanks to @Freezen for adding this problem and creating all test cases.
这是一个一位数组的简单处理,但是也凸显出自己在这方面思路匮乏。以下是一个时间复杂度为0(n^2)的不太好的解法,还在绞尽脑子的像一个快速的交换算法,以下的这个只能给60分。
另外送自己一句话,编程有兴趣,就要勤奋,不能三天打鱼两天晒网。
class Solution { public: void rotate(int num[], int n, int k) { int iTemp = 0; for(int iStep = 0; iStep != k; ++ iStep) { iTemp = num[n-1]; for(int i = n-1; i!=0; --i) { num[i] = num[i-1]; } num[0] = iTemp; } } };
这种弱爆了的状态还需要下一番功夫解决,多看书,多写程序!!!
时间: 2024-12-24 13:23:04