
Given a rotated sorted array, recover it to sorted array in-place. Example
[4, 5, 1, 2, 3] -> [1, 2, 3, 4, 5] Challenge
In-place, O(1) extra space and O(n) time. Clarification
What is rotated array: - For example, the orginal array is [1,2,3,4], The rotated array of it can be [1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3]
我的做法是先扫描不是ascending order的两个点,然后reverse array三次,分别是(0, i), (i+1, num.length-1), (0, num.length-1)
public class Solution {
/**
* @param nums: The rotated sorted array
* @return: The recovered sorted array
*/
public void recoverRotatedSortedArray(ArrayList<Integer> nums) {
// write your code
if (nums==null || nums.size()==0 || nums.size()==1) return;
int i = 0;
for (i=0; i<nums.size()-1; i++) {
if (nums.get(i) > nums.get(i+1)) break;
}
if (i == nums.size()-1) return;
reverse(nums, 0, i);
reverse(nums, i+1, nums.size()-1);
reverse(nums, 0, nums.size()-1);
} public void reverse(ArrayList<Integer> nums, int l, int r) {
while (l < r) {
int temp = nums.get(l);
nums.set(l, nums.get(r));
nums.set(r, temp);
l++;
r--;
}
}
}