标签:
Given a rotated sorted array, recover it to sorted array in-place.
Have you met this question in a real interview?
[4, 5, 1, 2, 3]
-> [1, 2, 3, 4, 5]
In-place, O(1) extra space and O(n) time.
What is rotated array?
1 public void recoverRotatedSortedArray(ArrayList<Integer> nums) 2 { 3 // write your code 4 if(nums.size()==0||nums.size()==1) return; 5 int i =0; 6 for(i=0; i<nums.size()-1;i++) 7 { 8 if(nums.get(i)>nums.get(i+1)) break; 9 } 10 if(i == nums.size()-1) return; 11 reverse(nums,0,i); 12 reverse(nums,i+1,nums.size()-1); 13 reverse(nums,0,nums.size()-1); 14 return; 15 16 17 } 18 19 20 public void reverse(ArrayList<Integer> nums, int left, int right) 21 { 22 while(left<right) 23 { 24 int temp = nums.get(left); 25 nums.set(left,nums.get(right)); 26 nums.set(right,temp); 27 left++; 28 right--; 29 30 } 31 32 return; 33 }
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4779854.html