题目描述
给定一个旋转排序数组,在原地恢复其排序。(升序)
样例
Example1:
[4, 5, 1, 2, 3] -> [1, 2, 3, 4, 5]
Example2:
[6,8,9,1,2] -> [1,2,6,8,9]
java题解
import java.util.ArrayList;
public class Solution {
private void reverse(ArrayList<Integer> nums, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
int temp = nums.get(i);
nums.set(i, nums.get(j));
nums.set(j, temp);
}
}
public void recoverRotatedSortedArray(ArrayList<Integer> nums) {
for (int index = 0; index < nums.size() - 1; index++) {
//找到第一个比后面的数大的数,以[4,5,1,2,3]为例,找到5,翻转[4,5]得到[5,4],翻转[1,2,3]得到[3,2,1]
//最后翻转[5,4,3,2,1]得到[1,2,3,4,5]
if (nums.get(index) > nums.get(index + 1)) {
reverse(nums, 0, index);
reverse(nums, index + 1, nums.size() - 1);
reverse(nums, 0, nums.size() - 1);
return;
}
}
}
}
C++题解
using namespace std;
class Solution {
public:
//辗转相除法求最大公约数
int getGCD(int a, int b) {
if (a % b == 0) {
return b;
}
return getGCD(b, a % b);
}
void recoverRotatedSortedArray(vector<int> &nums) {
int offset = 0;
for (int i = 1; i < nums.size(); i++) {
if (nums[i - 1] > nums[i]) {
offset = i;
}
}
if (offset == 0) {
return;
}
offset = nums.size() - offset;
int gcd = getGCD(offset, nums.size());
for (int i = 0; i < gcd; i++) {
int next = (i + offset) % nums.size();
//将每个数放到它们应该在的位置
while (next != i) {
int temp = nums[i]; nums[i] = nums[next]; nums[next] = temp;
next = (next + offset) % nums.size();
}
}
}
};
python题解
class Solution:
def recoverRotatedSortedArray(self, nums):
nums.sort()