移动数组:

将数组向后移动指定个数k,超出长度的移动到前面;
关键点:要从最后一个开始移动,将前一个数赋值给后面的,如果从前面开始移动,nums[0]移动到nums[1],会把nums[1]原来的值覆盖。
关键步k%=length;表示向后移动的个数,每次循环移动整体向后移动一个,k-1,并将最后一个赋值给第一个。

#include<iostream>
using namespace std;
#include<vector>
#include<deque>

class solution
{
public:
	void rotate(vector<int>& nums, int k)//移动数组
	{
		if (nums.empty())
		{
			return;
		}
		int length = nums.size();
		k %= length;
		while (k)
		{
			int temp = nums[length-1];
			for (int i = length - 1; i > 0; i--)
			{
				nums[i] = nums[i - 1];
			}
			nums[0] = temp;
			k--;
		}
	}

	void output(vector<int>&nums)//创建打印输出函数
	{
		
		for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++)
		{
			cout << *it << " ";
		}
		cout <<endl;
	}
};




int main()
{
	vector<int>nums;
	for (int i = 0; i < 10; i++)//给容器赋值
	{
		nums.push_back(i + 1);
	}
	solution s1;
	cout << "旋转前" << endl;
	s1.output(nums);
	int k = 2;
	s1.rotate(nums, k);
	cout << "旋转后" << endl;
	s1.output(nums);

	return 0;
}`

旋转前
1 2 3 4 5 6 7 8 9 10
旋转后
9 10 1 2 3 4 5 6 7 8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值