Leetcode189: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 [1,2,3,4,5,6,7] was 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.

Rotating an array

Solution One:

Using the exchange of data, for the above n=7,k=3 situation, can be divided into three steps to complete:

    1. Exchange 1234 is 4321
    2. Exchange 567 is 765
    3. Exchange 4321765 is 5671234

Divide the operation into three steps:
Time complexity is O (N), spatial complexity is O (1)

classSolution { Public://Solution 1: Using the swap    voidRotate vector<int>& Nums,intK) {intLength=nums.size ();        K=k%length; Swapvector (Nums,0, length-k-1); Swapvector (nums,length-k,length-1); Swapvector (Nums,0, length-1); }voidSwapvector ( vector<int>&nums,intFirstintLast) { for(inti=first,j=last;i<j;i++,j--) {swap (nums[i],nums[j]); }    }};
Solution Two:

Use a new array directly to hold the data, and then copy the new array to the given array.
The time complexity is O (n), and the spatial complexity is O (n).

class Solution {public:     //直接使用一块新的内存     void rotate(vector<int>int k) {          vector<int> result;          int length=nums.size();          k%=length;          result.insert(result.end(),nums.begin()+length-k,nums.end());          result.insert(result.end(),nums.begin(),nums.begin()+length-k);          nums=result;     }};

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode189:rotate Array

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.