时间复杂度O(N)是一定的
关键是空间复杂度
如果 直接copy一个数组中再copy回来 很简单 但是浪费空间
老师说记住就行了… 三步翻转法
基础知识补充
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]
细节:
算法复杂度O(n)。所以和面试官确认数组里有没有重复数字,如果有的话就直接用遍历法找最低点,二分的方法会有问题,反正不会增加时间复杂度。
public class Solution {
/**
* @param nums: An integer array
* @return: nothing
*/
public void recoverRotatedSortedArray(List<Integer> nums) {
// write your code here
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;
}
}
}
}