Recover Rotated Sorted Array

Given a rotated sorted array, recover it to sorted array in-place.

Have you met this question in a real interview?  
Yes
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]
此题目的意思,是说给定一个已经旋转过的数组,然后恢复为未旋转之前的数组;为了恢复,首先得知道数组旋转了多少次,所以先统计数组旋转的次数K,那么K之前是递增的,K之后也是递增的,如何恢复呢?这里巧妙的用到了反转,可以先将K之前的部分反转一次,然后K之后的部分反转一次,最后再全部反转一次,这样会发现,得到的数组,刚好是未旋转之前的数组。时间复杂度刚好为O(2 * N),空间复杂度为O(1).。
class Solution {
public:
    //找到最小值的下标,然后恢复原始数组顺序
    //恢复的时候,用反转,先整个反转一次,然后,每段分开反转一次
    void Swap(int &a, int &b)
    {
        a = a + b;
        b = a - b;
        a = a - b;
    }
    
    void recoverRotatedSortedArray(vector<int> &nums) {
        // write your code here
        int len = nums.size();
        if(len < 2)
            return;
        int k = 0;
        for(int i = 1; i < len; ++i)
        {
            if(nums[i] < nums[i - 1])
            {
                k = i;
                break;
            }
        }
        
        if(k == 0)
            return;
        
        //第一次反转前面部分
        int low = 0, high = k - 1;
        while(low < high)
        {
            Swap(nums[low], nums[high]);
            ++low;
            --high;
        }
        
        //第二次反转后面部分
        low = k; high = len - 1;
        while(low < high)
        {
            Swap(nums[low], nums[high]);
            ++low; --high;
        }
        
        //反转整个数组
        low = 0; high = len - 1;
        while(low < high)
        {
            Swap(nums[low], nums[high]);
            ++low; --high;
        }
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值