# [Leetcode 189] Rotate Array

Source: Internet
Author: User

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

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

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

[Show hint]

Related Problem:reverse Words in a String II

[Solution]

Save A[k, n-1] to temporary space, move a[0, K-1]. O (k) Secondary storage

`voidRotate (vector<int>& Nums,intk) {intn =nums.size (); if(n = =0|| K <=0)            return; K= k%N; Vector<int> buf (k,0);  for(inti =0; I < K; i++) Buf[i]= Nums[n-k +i];  for(inti = n-1; I >= K; i--) Nums[i]= Nums[i-K];  for(inti =0; I < K; i++) Nums[i]=Buf[i]; }`
`In situ Exchange:`
`The array consists of AB two parts, moving K positions to form a BA`
`Use R (a) to indicate the reverse order of a, then there is R (R (a)) = a`
`R (AB) = R (B) R (A)`
`Then R (B), R (A) are reversed to get BA`
`1 voidRotate (vector<int>& Nums,intk)2     {3         intn =nums.size ();4         if(n = =0|| K <=0)5             return;6             7K = k%N;8Reverse (Nums,0N1);9Reverse (Nums,0K1);TenReverse (nums, K, N-1); One     } A      -     voidReverse (vector<int>& Nums,intSinte) -     { the          for(inti = s, j = e; I < J; i++, j--) - swap (Nums[i], nums[j]); -}`

[Leetcode 189] Rotate Array

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.