1. 程式人生 > >Recover Rotated Sorted Array

Recover Rotated Sorted Array

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]

首先可以想到逐步移位,但是這種方法顯然太浪費時間,不可取。下面介紹利器『三步翻轉法』,以[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:

public class Solution {
    
/** * @param nums: The rotated sorted array * @return: The recovered sorted array */ public void recoverRotatedSortedArray(ArrayList<Integer> nums) { if (nums == null || nums.size() <= 1) { return; } int pos = 1; while (pos < nums.size()) { //
find the break point if (nums.get(pos - 1) > nums.get(pos)) { break; } pos++; } myRotate(nums, 0, pos - 1); myRotate(nums, pos, nums.size() - 1); myRotate(nums, 0, nums.size() - 1); } private void myRotate(ArrayList<Integer> nums, int left, int right) { // in-place rotate while (left < right) { int temp = nums.get(left); nums.set(left, nums.get(right)); nums.set(right, temp); left++; right--; } } }

C++:

/**
 * forked from
 * http://www.jiuzhang.com/solutions/recover-rotated-sorted-array/
 */
class Solution {
private:
    void reverse(vector<int> &nums, vector<int>::size_type start, vector<int>::size_type end) {
        for (vector<int>::size_type i = start, j = end; i < j; ++i, --j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }

public:
    void recoverRotatedSortedArray(vector<int> &nums) {
        for (vector<int>::size_type index = 0; index != nums.size() - 1; ++index) {
            if (nums[index] > nums[index + 1]) {
                reverse(nums, 0, index);
                reverse(nums, index + 1, nums.size() - 1);
                reverse(nums, 0, nums.size() - 1);

                return;
            }
        }
    }
};

原始碼分析

首先找到分割點,隨後分三步呼叫翻轉函式。簡單起見可將vector<int>::size_type替換為int