# 基础班 lintcode39 - Recover Rotated Sorted Array - easy

User u = new User(); u.setXXX(); u.getXXX(); 你想给他赋值就用u.setXXX(); 取这个类的对象的某个值 就get

Given a rotated sorted array, recover it to sorted array in-place.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]
Example
[4, 5, 1, 2, 3] -> [1, 2, 3, 4, 5]
Challenge
In-place, O(1) extra space and O(n) time.

1.用二分法找到断层处最低点a。
2.反转[0,a-1]，反转[a,end]，反转[0,end]

public class Solution {
/**
* @param nums: An integer array
* @return: nothing
*/
public void recoverRotatedSortedArray(List<Integer> nums) {
if (nums == null || nums.size() < 2) {
return;
}
int mark = findSmallestIndexWithDup(nums);
reverseSubarray(nums, 0, mark - 1);
reverseSubarray(nums, mark, nums.size() - 1);
reverseSubarray(nums, 0, nums.size() - 1);
}

private int findSmallestIndexWithDup(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
return i;
}
}
return 0;
}

private void reverseSubarray(List<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);
}
}
}


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++) {
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;
}
}
}
}


©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客