编程之美 2.17 数组循环移位
把一个含有N个元素的数组循环右移K位, 要求时间复杂度位O(N), 且只允许使用两个附加变量.
解法: 使用逆序方法, 分开两段求逆序, 再整体求逆序.
代码 (GCC 4.7.1):
/*
* BeautyOfProgramming.cpp
*
* Created on: 2013.11.7
* Author: Caroline
* Time: O(N)
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main (void) {
std::vector<std::string> sv =
{"a", "b", "c", "d", "1", "2", "3", "4"};
unsigned int n = 4;
std::cout << "array : ";
for(const auto s : sv)
std::cout << s << " ";
std::cout << std::endl;
std::reverse(sv.begin(), sv.begin()+4);
std::reverse(sv.begin()+4, sv.end());
std::reverse(sv.begin(), sv.end());
std::cout << "reverse (" << n <<") : ";
for(const auto s : sv)
std::cout << s << " ";
std::cout << std::endl;
return 0;
}