Recover Rotated Sorted Array
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]
////First, find out the index of the greatest number in the array,which means at this point ,it will greater than the next number.
///Second, partition the array to two part from the index
///Reverse them in partition.
///Reverse the whole array.
public class Solution { /** * @param nums: The rotated sorted array * @return: void */ public void recoverRotatedSortedArray(ArrayList<Integer> nums) { // write your code int n=nums.size(); int j=0; int k=j; for(int i=0;i<n-1;i++) { if(nums.get(i)>nums.get(i+1)) { reverse(nums,0,i); reverse(nums,i+1,n-1); reverse(nums,0,n-1); } } } public void reverse(ArrayList<Integer> nums, int start, int end) { int temp; while(start<end) { temp=nums.get(start); nums.set(start,nums.get(end)); nums.set(end,temp); start++; end--; } } }
时间: 2024-11-09 05:27:42