Rotate Array

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.


<pre name="code" class="cpp" style="color: rgb(51, 51, 51); font-size: 24.44444465637207px; line-height: 25.98958396911621px;">class Solution {
public:
    void rotate(vector<int>& nums, int k) {
      int temp;
      for(int i=0;i<k;i++)
      {
          temp=nums[nums.size()-1];
          for(int j=nums.size()-1;i>0;i--)
          {
              nums[i]=nums[i-1];
          }
          nums[0]=temp;
      }
    }
};

 
 

如果是k步,那么就是把后面k个放到前面了嘛。

我们先把整个数组reverse,然后把前面的reverse回来,再把后面的reverse回来

对于AB我们要通过reverse操作得到BA

那么先把AB reverse一次得到reverse(B)reverse(A)

然后再把reverse(B),reverse(A)分别reverse一次就得到了BA

 

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
      k=k%(nums.size());
       int n=nums.size();
      int a[n];
      for(int i=0;i<nums.size();i++)
      {
          a[i]=nums[i];
      }
     
        reverse(a, a + n);
        reverse(a, a + k);
        reverse(a + k, a + n);
     for(int i=0;i<n;i++)
      {
          nums[i]=a[i];
      }
    }
};

class Solution
{
	public:
		void swap(int * a,int * b)
		{
			int temp = *a;
			*a = *b;
			*b = temp;
		}

		void rotate(vector<int> & nums,int k)
		{
			int length = nums.size();
			int l = length - (k % length);
			int r = k % length;
			for(int i = 0,j = l - 1;i < j;i++,j--)
				swap(&nums[i],&nums[j]);
			for(int i = l,j = length - 1;i < j;i++,j--)
				swap(&nums[i],&nums[j]);
			for(int i = 0,j = length - 1;i < j;i++,j--)
				swap(&nums[i],&nums[j]);
		}
};


你可能感兴趣的:(Rotate Array)