LeetCode Rotate Array

Source: Internet
Author: User

LeetCode Rotate Array

Rotate Array Total Accepted: 12759 Total Submissions: 73112 My Submissions Question Solution
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.

Loop array. n indicates the length of the array, and k indicates the number of times the array is moved to the right.
Solution 1:

Class Solution {public: void rotate (int nums [], int n, int k) {if (n = 0) return; k = k % n; // when k is greater than n, n cycles return to the initial position. Therefore, if (k = 0) return can be omitted several times; int * s = new int [k]; // to expand and move in one step, apply for k extra space to save the removed element for (int I = 0; I
  
   
= 0; -- j) nums [j + k] = nums [j]; // move for (int I = 0; I
   
  

Extra space required O (k % n)
33/33 test cases passed.
Status: Accepted
Runtime: 29 MS

Solution 2 (obtain the network ):
Three-way flip: n-k before the first flip, k after the second flip, and all after the third flip.

class Solution {public: void rotate(int nums[], int n, int k) { if(n==0)return ; k=k%n; if(k==0)return ; reverse(nums,n-k,n-1); reverse(nums,0,n-k-1); reverse(nums,0,n-1); } void reverse(int nums[],int i,int j) { for(;i 

33 / 33 test cases passed.
Status: Accepted
Runtime: 26 ms

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.