设计一个算法,将以为数组A(下标从0开始)中的元素循环右移k位,要求只用一个元素大小的附加存储空间。给出空间的时间复杂度。

设计一个算法,将以为数组A(下标从0开始)中的元素循环右移k位,要求只用一个元素大小的附加存储空间。给出空间的时间复杂度。

1.暴力移位法——即一位一位移(时间的复杂度n*m)

#include <iostream>  
#include <string>  
using namespace std;
void rotate(string &str,int m){
	int n; 
	n=str.length();
	int i,temp;
	while(m--)
	{
		temp=str[n-1];
	for(i=n-2;i>=0;i--){
		str[i+1]=str[i];
	}
	str[0]=temp;
	}
}
int main()     
{     
    string ch="abcdefghijk";     
    rotate(ch,3);     
    cout<<ch<<endl;     
    return 0;        
} 

2.指针翻转法
思路:类似于快慢指针,设置两个指针p1,p2分别指向str【0】和str【m】两个值交换
这时候要注意p1指针指向最大的位置

  • List item

分类讨论下两种情况:
1.打个比方str【9】=abcdfeghi这个数组的长度为n=9,此时假设m=3,(注意)开始时候p1指向a,p2指向d,将abc看成干一个整体。因为abc这个整体中有3个,且str的总长度为3的倍数,此时不存在多余的情况
2.当str【11】=abcdfeghikl这个长度为n=11,m=3,此时n%m=2;

#include <iostream>  
#include <string>  
using namespace std;
void rotate(string &str,int m){
	int n,i; 
	n=str.length();
	int p1,p2;
	p1=0;
	p2=m;
	 if (str.length() == 0 || m <= 0)  
        return;
    int k=(n-m)-n%m;
	  
	while(k--)
	{
	  swap(str[p1], str[p2]);  
        p1++;  
        p2++; 
	}
	int r=n-p2;
	while(r--)
	{
		i=p1;
		while(i<p2)
		{
			swap(str[i], str[p2]);
			i++;
		}
		
	}
	
}
int main()     
{     
    string ch="abcdefghijklm";     
    rotate(ch,3);     
    cout<<ch<<endl;     
    return 0;        
} 

猜你喜欢

转载自blog.csdn.net/weixin_43904021/article/details/87905483