题目:
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]
1 /** 2 * 本代码由九章算法编辑提供。没有版权欢迎转发。 3 * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 4 * - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班 5 * - 更多详情请见官方网站:http://www.jiuzhang.com/ 6 */ 7 8 import java.util.ArrayList; 9 10 11 public class Solution { 12 /** 13 * @param nums: The rotated sorted array 14 * @return: The recovered sorted array 15 */ 16 private void reverse(ArrayList<Integer> nums, int start, int end) { 17 for (int i = start, j = end; i < j; i++, j--) { 18 int temp = nums.get(i); 19 nums.set(i, nums.get(j)); 20 nums.set(j, temp); 21 } 22 } 23 24 public void recoverRotatedSortedArray(ArrayList<Integer> nums) { 25 for (int index = 0; index < nums.size() - 1; index++) { 26 if (nums.get(index) > nums.get(index + 1)) { 27 reverse(nums, 0, index); 28 reverse(nums, index + 1, nums.size() - 1); 29 reverse(nums, 0, nums.size() - 1); 30 return; 31 } 32 } 33 } 34 }