189. Rotate array from right to start flipping arrays

Source: Internet
Author: User
Tags array length

[Copy question]:

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

[Brute force solution]:

Time Analysis:

Spatial Analysis:

[After optimization]:

Time Analysis:

Spatial Analysis:

[Wonderful output CONDITIONS]:

[Wonderful corner case]:

[Thinking questions]:

    1. The swap function is forgotten, and it's drunk.
    2. K-Step may be large, so%= array length is required

[a sentence of thought]:

[input]: null: Normal: Large: Extra Small: Special cases handled in the program: abnormal conditions (unreasonable input):

[Drawing]:

From left to right:

[One brush]:

    1. The swap function needs to be brought into index, so the internal I J does not need to be initialized

[Two brushes]:

[Three brushes]:

[Four brushes]:

[Five brushes]:

[Results of five-minute visual debug]:

[Summary]:

Reverse are all using the Swap function, and the routines are the same.

[Complexity]:time Complexity:o (n) Space complexity:o (1)

[English data structure or algorithm, why not other data structures or algorithms]:

[Key templating code]:

Swap

 Public void swap (intint int j) {        while (i < j) {              int temp = nums[i];             = Nums[j];             = temp;                        I+ +;            J--;        }

[Other solutions]:

[Follow up]:

[The problem given by the LC becomes variable]:

All the questions of swap

[Code Style]:

classSolution { Public voidRotateint[] Nums,intk) {//cc        if(Nums = =NULL|| Nums.length = = 0) {            return ; }                //INI, KK%=nums.length; //SwapSwap (nums, 0, nums.length-k-1); Swap (nums, Nums.length-K, Nums.length-1); Swap (Nums,0, Nums.length-1); //return    }         Public voidSwap (int[] Nums,intIintj) { while(I <j) {inttemp =Nums[i]; Nums[i]=Nums[j]; NUMS[J]=temp; I++; J--; }    }}
View Code

189. Rotate array from right to start flipping arrays

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.