2) O(n) space, O(n) time
3) 3 time reverse, O(1) space, O(n) time
public class Solution {
/**
* @param nums: The rotated sorted array
* @return: The recovered sorted array
*/
public void recoverRotatedSortedArray(ArrayList<Integer> nums) {
// write your code
int i;
for (i = 1; i < nums.size(); i++) {
if (nums.get(i) < nums.get(i - 1)) {
break;
}
}
reverse(nums, 0, i - 1);
reverse(nums, i, nums.size() - 1);
reverse(nums, 0, nums.size() - 1);
}
private void reverse(ArrayList<Integer> nums, int start, int end) {
for (; start < end; start++, end--) {
int tmp = nums.get(start);
nums.set(start, nums.get(end));
nums.set(end, tmp);
}
}
}
没有评论:
发表评论