Recover Rotated Sorted Array

Question

  1. Given a rotated sorted array, recover it to sorted array in-place.
  2. Example
  3. [4, 5, 1, 2, 3] -> [1, 2, 3, 4, 5]
  4. Challenge
  5. In-place, O(1) extra space and O(n) time.
  6. Clarification
  7. What is rotated array:
  8. - 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]

首先可以想到逐步移位,但是这种方法显然太浪费时间,不可取。下面介绍利器『三步翻转法』,以[4, 5, 1, 2, 3]为例。

  1. 首先找到分割点51
  2. 翻转前半部分4, 55, 4,后半部分1, 2, 3翻转为3, 2, 1。整个数组目前变为[5, 4, 3, 2, 1]
  3. 最后整体翻转即可得[1, 2, 3, 4, 5]

由以上3个步骤可知其核心为『翻转』的in-place实现。使用两个指针,一个指头,一个指尾,使用for循环移位交换即可。

Java

  1. public class Solution {
  2. /**
  3. * @param nums: The rotated sorted array
  4. * @return: The recovered sorted array
  5. */
  6. public void recoverRotatedSortedArray(ArrayList<Integer> nums) {
  7. if (nums == null || nums.size() <= 1) {
  8. return;
  9. }
  10. int pos = 1;
  11. while (pos < nums.size()) { // find the break point
  12. if (nums.get(pos - 1) > nums.get(pos)) {
  13. break;
  14. }
  15. pos++;
  16. }
  17. myRotate(nums, 0, pos - 1);
  18. myRotate(nums, pos, nums.size() - 1);
  19. myRotate(nums, 0, nums.size() - 1);
  20. }
  21. private void myRotate(ArrayList<Integer> nums, int left, int right) { // in-place rotate
  22. while (left < right) {
  23. int temp = nums.get(left);
  24. nums.set(left, nums.get(right));
  25. nums.set(right, temp);
  26. left++;
  27. right--;
  28. }
  29. }
  30. }

C++

  1. /**
  2. * forked from
  3. * http://www.jiuzhang.com/solutions/recover-rotated-sorted-array/
  4. */
  5. class Solution {
  6. private:
  7. void reverse(vector<int> &nums, vector<int>::size_type start, vector<int>::size_type end) {
  8. for (vector<int>::size_type i = start, j = end; i < j; ++i, --j) {
  9. int temp = nums[i];
  10. nums[i] = nums[j];
  11. nums[j] = temp;
  12. }
  13. }
  14. public:
  15. void recoverRotatedSortedArray(vector<int> &nums) {
  16. for (vector<int>::size_type index = 0; index != nums.size() - 1; ++index) {
  17. if (nums[index] > nums[index + 1]) {
  18. reverse(nums, 0, index);
  19. reverse(nums, index + 1, nums.size() - 1);
  20. reverse(nums, 0, nums.size() - 1);
  21. return;
  22. }
  23. }
  24. }
  25. };

源码分析

首先找到分割点,随后分三步调用翻转函数。简单起见可将vector<int>::size_type替换为int