Recover Rotated Sorted Array
Given a rotated sorted array, recover it to sorted array in-place.
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]
Example
[4, 5, 1, 2, 3] -> [1, 2, 3, 4, 5]
分析:
利用公式 (A^TB^T)^T = BA
1 public class Solution { 2 3 public void recoverRotatedSortedArray(ArrayList<Integer> nums) { 4 if (nums == null || nums.size() == 0 || nums.size() == 1) return; 5 int i = 0; 6 for (; i < nums.size() - 1; i++) { 7 if (nums.get(i) > nums.get(i + 1)) 8 break; 9 } 10 if (i == nums.size() - 1) return; 11 reverse(nums, 0, i); 12 reverse(nums, i + 1, nums.size() - 1); 13 reverse(nums, 0, nums.size() - 1); 14 } 15 16 public void reverse(ArrayList<Integer> nums, int l, int r) { 17 while (l < r) { 18 int temp = nums.get(l); 19 nums.set(l, nums.get(r)); 20 nums.set(r, temp); 21 l++; 22 r--; 23 } 24 } 25 }

浙公网安备 33010602011771号