rotate array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

Hint:
Could you do it in-place with O(1) extra space?

Related problem: Reverse Words in a String II

#include<iostream>
using namespace std;

class Solution {
public:
	void rotate(int nums[], int n, int k) /* solution one */
	{  //时间复杂度为O(k*n);空间复杂度O(1)
		int temp;
		for (int i = 0; i < k; i++)
		{
			temp = nums[n - 1];
			for (int j = n - 2; j >= 0; j--)
			{
				nums[j+1] = nums[j];
			}
			nums[0] = temp;
		}

	}
	void rotate2(int nums[], int n, int k) /* solution two */
	{
		k = k%n;
		int *temp = new int[n];
		memcpy(temp, nums + n - k, sizeof(int)*k);
		memcpy(temp+k,nums,sizeof(int)*(n-k));
		memcpy(nums, temp, sizeof(int)*n);
		delete[] temp;
		/*
		void *memcpy(void *dest, const void *src, size_t n);
		c和c++使用的内存拷贝函数,memcpy函数的功能是从源src所指的内存地址的起始位置开始
		拷贝n个字节到目标dest所指的内存地址的起始位置中。
		注意:dest和src在内存的位置,可能会产生覆盖的情况。		
		*/
	}
      void reverse(int nums[], int start, int end)
      {
	  int i = 0;
	  while (start < end)
	  {
		int tmp = nums[start];
		nums[start] = nums[end];
		nums[end] = tmp;
		start++;
		end--;
	  }
      }
     void rotateArray3(int nums[],int n, int k)
     { //最优效率的方法,时间复杂度为O(n);空间复杂度为O(1)
	  reverse(nums, 0, n - k-1 );
	  reverse(nums, n - k, n-1);
	  reverse(nums, 0, n - 1);
     }
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值