LeetCode 189——旋转数组,用O(1)的空间复杂度实现

本文介绍了一种基于数组长度和旋转位数最大公约数的数组旋转算法。通过具体实例展示了如何实现数组元素的有效移动,以及算法背后的数学原理。适用于理解数组操作及算法优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

旋转的次数是,数组长度n 和 旋转位数  k的最大公约数

折腾了俩小时才琢磨出来,笨死我了

#include<iostream>
#include<vector>
#include<string>
#include<ctime>
#include<queue>
#include<cassert>
#include<algorithm>

using namespace std;


class Solution {
public:
	void rotate(vector<int>& nums, int k) {
		int cur_index,next_index,cur;
		int n = nums.size();
		cout <<"n:"<< n << endl;
		cout << "k:" << k<< endl;
		//i属于[0.......n-k-1]时,应该往后移k位,+k
		//i属于[n-k......n-1]时,下标变为i-(n-k)
		k = k%n;
		if (n == 0 || n == 1||k==0)
			return;

		//旋转的次数就是n和k的最大公约数
		//求n和k的
		int a = n,b = k;
		while (a != b)
		{
			if (a>b)
			{
				a = a - b;
			}
			else
			{
				b = b - a;
			}
		}

		int rotate_count = a;
		cout << "rotate:" << rotate_count << endl;

		for (int i = 1; i <= rotate_count; i++)
		{
			cur_index = n - k - i;
			cur = nums[cur_index];
			next_index = cur_index + k;
			int temp = nums[next_index];
			nums[next_index] = cur;
			cur = temp;
			cur_index = next_index;

			while (cur_index != n - k - i)
			{
				if (cur_index >= 0 && cur_index <= n - k - 1)
				{
					next_index = cur_index + k;
					int temp = nums[next_index];
					nums[next_index] = cur;
					cur = temp;
					cur_index = next_index;

				}
				if (cur_index >= n - k && cur_index <= n - 1)
				{
					next_index = cur_index - (n - k);
					int temp = nums[next_index];
					nums[next_index] = cur;
					cur = temp;
					cur_index = next_index;

				}
			}


			cout << "开始第"<<i<<"部分旋转" << endl;
			for (int i = 0; i < n; i++)
				cout << nums[i] << " ";
			cout << endl;
		}
	}
};
int main()
{
	vector<int> arr = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54 };
	//vector<int> arr = { 1,2,3,4,5,6,7,8,9,10 };
	Solution().rotate(arr,45);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值