您的位置:首页 > 其它

Recover Rotated Sorted Array

2015-08-05 15:49 330 查看
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;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Recover Rotated Sort