C++实现一维向量旋转算法
在《编程珠玑》一书的第二章提到了n元一维向量旋转算法(又称数组循环移位算法)的五种思路,并且比较了它们在时间和空间性能上的区别和优劣。本文将就这一算法做较为深入的分析。具体如下所示:
一、问题描述
将一个n元一维向量向左旋转i个位置。例如,假设n=8,i=3,向量abcdefgh旋转为向量defghabc。简单的代码使用一个n元的中间向量在n步内可完成该工作。你能否仅使用几十个额外字节的内存空间,在正比于n的时间内完成向量的旋转?
二、解决方案
思路一:将向量x中的前i个元素复制到一个临时数组中,接着将余下的n-i个元素左移i个位置,然后再将前i个元素从临时数组中复制到x中余下的位置。
性能:这种方法使用了i个额外的位置,如果i很大则产生了过大的存储空间的消耗。
C++代码实现如下:
/************************************************************************* > File Name: vector_rotate.cpp > Author: SongLee ************************************************************************/ #include<iostream> #include<string> using namespace std; int main() { string s = "abcdefghijklmn"; cout << "The origin is: " << s << endl; // 左移个数 int i; cin >> i; if(i > s.size()) { i = i%s.size(); } // 将前i个元素临时保存 string tmp(s, 0, i); // 将剩余的左移i个位置 for(int j=i; j<s.size(); ++j) { s[j-i] = s[j]; } s = s.substr(0, s.size()-i) + tmp; cout << "The result is: "<< s << endl; return 0; }
思路二:定义一个函数将x向左旋转一个位置(其时间正比于n),然后调用该函数i次。
性能:这种方法虽然空间复杂度为O(1),但产生了过多的运行时间消耗。
C++代码实现如下:
/************************************************************************* > File Name: vector_rotate_1.cpp > Author: SongLee ************************************************************************/ #include<iostream> #include<string> using namespace std; void rotateOnce(string &s) { char tmp = s[0]; int i; for(i=1; i<s.size(); ++i) { s[i-1] = s[i]; } s[i-1] = tmp; } int main() { string s = "abcdefghijklmn"; cout << "The origin is: " << s << endl; // 左移个数 int i; cin >> i; if(i > s.size()) { i = i%s.size(); } // 调用函数i次 while(i--) { rotateOnce(s); } cout << "The result is: "<< s << endl; return 0; }
思路三:移动x[0]到临时变量t中,然后移动x[i]到x[0]中,x[2i]到x[i],依次类推,直到我们又回到x[0]的位置提取元素,此时改为从临时变量t中提取元素,然后结束该过程(当下标大于n时对n取模或者减去n)。如果该过程没有移动全部的元素,就从x[1]开始再次进行移动,总共移动i和n的最大公约数次。
性能:这种方法非常精巧,像书中所说的一样堪称巧妙的杂技表演。空间复杂度为O(1),时间复杂度为线性时间,满足问题的性能要求,但还不是最佳。
C++代码实现如下:
/************************************************************************* > File Name: vector_rotate_2.cpp > Author: SongLee ************************************************************************/ #include<iostream> #include<string> using namespace std; // 欧几里德(辗转相除)算法求最大公约数 int gcd(int i, int j) { while(1) { if(i > j) { i = i%j; if(i == 0) { return j; } } if(j > i) { j = j%i; if(j == 0) { return i; } } } } int main() { string s = "abcdefghijklmn"; cout << "The origin is: "<< s << endl; // 左移个数 int i; cin >> i; if(i > s.size()) { i = i%s.size(); } // 移动 char tmp; int times = gcd(s.size(), i); for(int j=0; j<times; ++j) { tmp = s[j]; int pre = j; // 记录上一次的位置 while(1) { int t = pre+i; if(t >= s.size()) t = t-s.size(); if(t == j) // 直到tmp原来的位置j为止 break; s[pre] = s[t]; pre = t; } s[pre] = tmp; } cout << "The result is: "<< s << endl; return 0; }
- 上一篇:C++变位词问题分析
- 下一篇:C++实现位图排序实例