OJ Practice 36--t189 Rotate Array

Source: Internet
Author: User

The rotate operation of the array for a given number of times.

Rotate once: The end element is placed at the beginning, and the other elements are cycled to the right one unit.

Ideas

1. Open a space where the k elements at the end are placed in the beginning of the new array in the previous order, and the remaining elements of the original array are assigned to the remaining space in the new array in the order of the former.

It saves time complexity and increases the complexity of space.

2. Forward thinking, each processing once rotate, the last element bubbles to the beginning. The complexity of the time is too high.

3. Replace the rotate with an exchange, the array is divided into two halves, the first half is flipped, the second half is flipped, the final whole is flipped, the time complexity and space complexity are the lowest.

"My Code"

voidRotateintNums[],intNintk) {intk1=k%N; Reverse (Nums,0, n-k1-1); Reverse (nums, n-K1, N-1); Reverse (Nums,0, N-1); }    voidReverseintNums[],intLinth) {        //swap instead of flipping        inttemp; intMid= (L+H)/2;  for(intI=l; i<=mid; i++) {Temp=Nums[i]; Nums[i]=nums[h-i+L]; Nums[h-i+l]=temp; }    }

PostScript

Time consuming 27ms, ranked top.

So, the previously learned algorithm is still useful, inadvertently will be remembered.

OJ Practice 36--t189 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.