Recover Rotated Sorted Array(Easy)

From Lintcode

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] Challenge

In-place, O(1) extra space and O(n) time.

解题思路

我的做法是先扫描不是ascending order的两个点,然后reverse array三次,分别是(0, i), (i+1, num.length-1), (0, num.length-1)

public void recoverRotatedSortedArray(ArrayList<Integer> nums) {
         // write your code
         if (nums==null || nums.size()==0 || nums.size()==1) return;
         int i = 0;
         for (i=0; i<nums.size()-1; i++) {
             if (nums.get(i) > nums.get(i+1)) break;
         }
         if (i == nums.size()-1) return;
         reverse(nums, 0, i);
         reverse(nums, i+1, nums.size()-1);
         reverse(nums, 0, nums.size()-1);
     }

     public void reverse(ArrayList<Integer> nums, int l, int r) {
         while (l < r) {
             int temp = nums.get(l);
             nums.set(l, nums.get(r));
             nums.set(r, temp);
             l++;
             r--;
         }
     }

results matching ""

    No results matching ""