# [Leetcode 189] rotate Array

Source: Internet
Author: User

1. Question

Rotate an arrayNElements to the rightKSteps.

For example,N= 7 andK= 3, the array`[1,2,3,4,5,6,7]`Is rotated`[5,6,7,1,2,3,4]`.

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

[Show hint]

Hint:
Cocould You Do It In-Place with O (1) extra space?

Credits:
Special thanks to @ freezen for adding this problem and creating all test cases.

The hide tags array 2 idea was previously viewed in "programming Pearl". First, the first part is rotated, then the last part is selected, and then the whole part is rotated. The result is displayed. the time complexity O (N ), space O (1) is a good algorithm. It can be used to move a row in a text editor. 3 code
`Public void rotate (INT [] Nums, int K) {int Len = nums. length; K % = Len; // it is important to prevent K from exceeding Len this. partrotate (Nums, 0, len-k); this. partrotate (Nums, len-K, Len); // as to why not Len-k-1 is related to the following implementation. This. partrotate (Nums, 0, Len);} public int [] partrotate (INT [] Nums, int head, int rear) {int temp = 0; For (INT I = 0; I <(rear-head)/2; I ++) {temp = Nums [head + I]; Nums [head + I] = Nums [rear-I-1]; nums [rear-I-1] = temp;} return Nums ;}`

[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.