Happyleetcode50: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] .

Although this problem has been done, it is obviously not the optimal solution. Obviously space requirements are not met.

One thing to pay particular attention, in the beginning I was the default k is less than N, in fact, K can be greater than n, so after modifying the code, we use K to the N to take the remainder.

My idea is to move the previous value in the array first to the back. The following values are stored in a vector before being replaced, and after the previous values are arranged, the data in the vector is taken out and placed in front of the new array.

The code is as follows:

classSolution { Public:    voidRotateintNums[],intNintk) {if(nums = = NULL | | n <=0 )            return; K= k%N; Vector<int>Tempsave;        Tempsave.reserve (k); intCount =0;//record how much data has been pushed.         for(inti = n-k-1; I >=0; --i) {if(Count <k) {Tempsave.push_back (nums[i+K]); Count++; } nums[i+ K] =Nums[i]; }        intTemp =tempsave.size (); if(Tempsave.size () <k) { for(inti = k-1; I >= Temp; --i) tempsave.push_back (Nums[i]); }         for(inti =0; I < K; ++i) {nums[i]=Tempsave.back ();        Tempsave.pop_back (); }        }};

In fact, there are some simpler ways to think about it, such as copying the array once, and then cutting out the part of the array that you need according to the situation.

classSolution { Public:    voidRotateintNums[],intNintk) {k= k%N; int* Newnums =New intN2];  for(inti =0; I < n; ++i) {newnums[i]=Nums[i]; Newnums[i+ N] =Nums[i]; }        //int res = n-k;         for(inti =0; I < n; ++i) {nums[i]= Newnums[i + N-K]; }    }};
The amount of code is significantly shorter.

Happyleetcode50: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.