(Leetcode 189) 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] .

Topic:

Gives an array, n elements, moves the array to the right to move the k elements in a loop.

Ideas:

Note that the requirements of the topic are circular movement, so k can be any non-negative integer, but the number of array elements is n, so k=k%n.

A common idea is to:

1. Flip the entire array: a[0...n-1]; e.g. [7,6,5,4,3,2,1]

2, flip the array before K: a[0,k-1], such as [5,6,7,4,3,2,1]

3, flip the array after n-k: a[k,n-1], such as [5,6,7,1,2,3,4]

Similar applications: Flip all the words in a sentence, and the word content does not change.

Code:
classSolution { Public:    voidReverseintNums[],intIintj) {         while(i<j) {            inttmp=Nums[i]; Nums[i]=Nums[j]; NUMS[J]=tmp; I++; J--; }    }        voidRotateintNums[],intNintk) {k=k%N; if(k>=1&& n>1&& k<=N) {Reverse (nums,0, N-1); Reverse (Nums,0, K-1); Reverse (Nums,k,n-1); }    }};

(Leetcode 189) 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.