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