[LeetCode] 189. Rotate Array

Source: Internet
Author: User

[LeetCode] 189. Rotate Array

Question

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

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

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

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

Train of Thought 1

The same idea as the string rotation operation.
Three-way flip: n-k before the first flip, k after the second flip, and all after the third flip.

Code 1

/* ---------------------------------------- * Date: 2014-02-25 * Author: SJF0115 * Title: 189. Rotate Array * URL: https://oj.leetcode.com/problems/rotate-array/ * result: AC * Source: LeetCode * blog: Author */# include
  
   
# Include
   
    
Using namespace std; class Solution {public: void rotate (int nums [], int n, int k) {if (n <= 1) {return ;} // if k = k % n; if (k <= 0) {return;} // if // n-k Reverse (nums, 0, n-k-1); // k Reverse (nums, n-k, n-1) After flip; // flip all Reverse (nums, 0, n-1);} private: void Reverse (int nums [], int left, int right) {int tmp; for (int I = left, j = right; I <j; ++ I, -- j) {// swap (nums [I], nums [j]) ;}// for}; int main () {Solution solution; int A [] = {1, 2, 4, 5, 6, 7}; int n = 7; int k = 2; solution. rotate (A, n, k); for (int I = 0; I <n; ++ I) {cout <
   
  

Contact Us

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.