Topic:
restoring a rotated sorted array
Given a rotated sorted array, restore its sort in place.
Sample Example
[4, 5, 1, 2, 3]
-[1, 2, 3, 4, 5]
challenges
Extra Space with O (1) and O (n) time complexity
Description
What is a rotating array?
- For example, the original array is [1,2,3,4], then its rotation array can be [1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3]
Solving:
Start I think, first find the middle of the critical point, and then in the sort, the critical point found, sort of do not know how to do, here, see a good way, the first half of the reverse, the second half of the reverse, the whole again continue.
Java Program:
Public classSolution {/** * @paramnums:the rotated sorted array *@return: void*/ Public voidRecoverrotatedsortedarray (arraylist<integer>nums) { //Write your code intNumslen =nums.size (); intI=0; for(i=0;i<numslen-1;i++){ if(Nums.get (i) >nums.get (i+1) {reverse (nums,0, i); Reverse (nums,i+1,numslen-1); Reverse (Nums,0,numslen-1); } } } Public voidReverse (arraylist<integer> nums,intStartintend) { while(start<end) { intTMP =nums.get (start); Nums.set (Start,nums.get (end)); Nums.set (END,TMP); Start++; End--; } }}
View Code
Total time: 1414 Ms
And then I see that this method is used on the internet ....
Python program:
classSolution:"""@param nums:the Rotated sorted array @return: nothing""" defRecoverrotatedsortedarray (Self, nums):#Write your code here ifnums==None:returnNumslen=Len (nums) forIndexinchRange (numslen-1): if(nums[index]>nums[index+1]): Self.reverse (Nums,0,index) self.reverse (Nums,index+1,numslen-1) Self.reverse (Nums,0,numslen-1) defreverse (self,nums,start,end): whilestart<End:self.swap (nums,start,end) Start+=1End-=1defSwap (self,nums,start,end): TMP=Nums[start] Nums[start]=Nums[end] Nums[end]= tmp
View Code
Total time: 228 ms
Lintcode Easy title: Recover rotated Sorted Array recovery rotation sorted array