Given a rotated sorted array, recover it to sorted array in-place.
Have you met this question in a real interview?[4, 5, 1, 2, 3]
-> [1,
2, 3, 4, 5]
In-place, O(1) extra space and O(n) time.
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]
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;
}
}
};