Given a rotated sorted array, recover it to sorted array in-place.
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]
解题思路:
技巧题:知道就知道题,不知道就拉倒题。
找到分割位置,什么时候出现下降就是分割位置。
三步翻转法:
- [1,2,3]翻转一下变成[3,2,1]
- [4,5]翻转变成[5,4]
- 最后全部翻转一下就得到。
相关类似题目:
- Rotate String: abcdefg, offset = 3 -> efgabcd
方法:三步翻转法:
(1) adcd efg
(2) dcda gfe
(3) efgabcd
- Rotate Words List: I love you -> you love I
方法:二步翻转法:
(1)全部翻转
(2)根据空格每个单词翻转
Java code:
public class Solution { /** * @param nums: The rotated sorted array * @return: void */ public void recoverRotatedSortedArray(ArrayList<Integer> nums) { // write your code for(int i = 0; i < nums.size() - 1 ; i++) { if(nums.get(i) > nums.get(i+1)) { reverse(nums, 0, i); reverse(nums, i+1, nums.size()-1); reverse(nums, 0 , nums.size()-1); return; } } } public 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); } } }
Reference:
1. http://www.jiuzhang.com/solutions/recover-rotated-sorted-array/