Recover Rotated Sorted Array

Posted 北叶青藤

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 

以上是关于Recover Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-easy-Recover Rotated Sorted Array

153. Find Minimum in Rotated Sorted Array

LC.153.Find Minimum in Rotated Sorted Array

#Leetcode# 153. Find Minimum in Rotated Sorted Array

LC.154. Find Minimum in Rotated Sorted Array II

#Leetcode# 154. Find Minimum in Rotated Sorted Array II