Problem: Given a rotated sorted array, recover the sorted array in-place.
For example:
{ 4, 5, 1, 2, 3 } –> {1, 2, 3, 4, 5}
Challenge requirement:
in-palce, O(1) extra space and O(n) time
Solution:
3-step reverse operation
Step 1: find two different sub array sections {4, 5}, {1, 2, 3}
Step 2. reverse sub array elements to: {5, 4}, { 3, 2, 1}
Step 3: reverse all array elements to {1, 2, 3, 4, 5}
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public void recoverRotatedSortedArray(ArrayList<Integer> nums) { if(nums.size() <= 1) { return; } // do nothing if(nums.get(0) < nums.get(nums.size() - 1)) { // do nothing return; } int pt = 0; for(int i = 0; i < nums.size() - 1; i++) { if(nums.get(i) > nums.get(i+1)) { pt = i; } } for(int start = 0, end = pt; start < end; start++, end--) { swap(nums, start, end); } for(int start = pt+1, end = nums.size() - 1; start < end; start++, end--) { swap(nums, start, end); } for(int start = 0, end = nums.size() - 1; start < end; start++, end--) { swap(nums, start, end); } } private void swap(ArrayList<Integer> nums, int start, int end) { int tmp = nums.get(start); nums.set(start, nums.get(end)); nums.set(end, tmp); } |