189. Rotate Array Java Solutions

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

Note:
Try to come up as many solutions as can, there is at least 3 different ways to solve this problem.

[Show hint]

Hint:
Could do it in-place with O (1) extra space?

Related Problem:reverse Words in a String II

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

1  Public classSolution {2      Public voidRotateint[] Nums,intk) {3         int[] tmp =New int[K];4         intLen =nums.length;5K%=len;//processing k greater than the array length6          for(inti = 0; I < K; i++){7Tmp[i] = nums[len-k+i];8         }9len--;Ten          for(inti = len-k; i>= 0; i--){ Onenums[len--] =Nums[i]; A         } -          for(inti = 0; I < K; i++){ -Nums[i] =Tmp[i]; the         } -     } -}

Solution two to the array 0~len-1 inverted once, 0~k-1 reverse, k~len-1 reverse once, you can get the answer:

1  Public classSolution {2      Public voidRotateint[] Nums,intk) {3         intLen =nums.length;4K%=Len;5Reverse (nums,0,len-1);6Reverse (nums,0,k-1);7Reverse (nums,k,len-1);8     }9     Ten      Public voidReverseint[] Nums,intSinte) { One          while(S <=e) { A             intTMP =Nums[s]; -Nums[s] =Nums[e]; -Nums[e] =tmp; thes++; -e--; -         } -     } +}

189. Rotate Array Java Solutions

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.