Lintcode-easy-recover Rotated Sorted Array

Source: Internet
Author: User

Given a rotated sorted array, recover it to sorted array in-place.

[4, 5, 1, 2, 3]-[1, 2, 3, 4, 5]

The method is very strange, remember just fine:

Find the demarcation point, reverse the left half, reverse the right side, this time the entire array is from large to small arrangement, and then the entire array reversal can be.

But be aware that this array is not rotate, so start by judging it first.

 Public classSolution {/**     * @paramnums:the rotated sorted array *@return: void*/     Public voidRecoverrotatedsortedarray (arraylist<integer>nums) {        //Write your code        if(Nums = =NULL|| Nums.size () <= 1)            return; if(Nums.get (0) < Nums.get (Nums.size ()-1))            return; intFlag = 0;  for(inti = 0; I < Nums.size ()-2; i++){            if(Nums.get (i) > nums.get (i + 1) ) {flag=i;  Break; }} reverse (Nums,0, flag); Reverse (nums, flag+ 1, Nums.size ()-1); Reverse (Nums,0, Nums.size ()-1); return; }         Public voidReverse (arraylist<integer> nums,intStartintend) {        if(Start >end)return; intleft =start; intright =end;  while(Left <Right ) {            inttemp =Nums.get (left);            Nums.set (left, Nums.get (right));                        Nums.set (right, temp); Left++; Right--; }                return; }    }

Lintcode-easy-recover Rotated Sorted 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.