#39 Recover Rotated Sorted Array

原创 2016年08月29日 04:08:27

题目描述:

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.

题目思路:

看到这题真是傻眼了很久,一直想的是怎么一个一个去in-place。。。这个array不顺(不是in order)但是可以分成顺的两截:一截从小到大,一截从小到大。那么如果把这两截分别reverse,这俩就顺利的接起来了。再整体reverse一下就是答案了!

Mycode(AC = 17ms):

</pre><pre name="code" class="cpp">class Solution {
public:
    void recoverRotatedSortedArray(vector<int> &nums) {
        // write your code here
        if (nums.size() <= 1) return;
        
        for (int i = 0; i < nums.size() - 1; i++) {
            if (nums[i] > nums[i + 1]) {
                // 4,5,1,2,3 -> 4,5,3,2,1
                reverse(nums.begin() + i + 1, nums.end());
                // 4,5,3,2,1 -> 5,4,3,2,1
                reverse(nums.begin(), nums.begin() + i + 1);
                // 5,4,3,2,1 -> 1,2,3,4,5
                reverse(nums.begin(), nums.end());
                return;
            }
        }
        
        return;
    }
    
};



版权声明:三千微尘里,吾宁爱与憎

Recover Rotated Sorted Array

Given a rotated sorted array, recover it to sorted array in-place. Have you met this question i...

【LeetCode-面试算法经典-Java实现】【153-Find Minimum in Rotated Sorted Array(找旋转数组中的最小数字)】

【153-Find Minimum in Rotated Sorted Array(找旋转数组中的最小数字)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Suppose...

【LeetCode-面试算法经典-Java实现】【154-Find Minimum in Rotated Sorted Array II(找旋转数组中的最小数字II)】

【154-Find Minimum in Rotated Sorted Array II(找旋转数组中的最小数字II)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Fo...

【LeetCode-面试算法经典-Java实现】【033-Search in Rotated Sorted Array(在旋转数组中搜索)】

【033-Search in Rotated Sorted Array(在旋转数组中搜索)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Suppose a sorted...

[LeetCode][Java] Search in Rotated Sorted Array II

题目: Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed? Would t...

leetcode(33). Search in Rotated Sorted Array

problem Suppose an array sorted in ascending order is rotated at some pivot unknown to you befo...

LeetCode Solutions : Find Minimum in Rotated Sorted Array

【算法思路】利用折半查找的思路去查找这个最小元素 【编程步骤】 * 1. 如果数组num只有一个元素,则所求的最小的元素就是它了; * 2. 若left到right位置的元素严格递增,则最小的元素...
  • lviiii
  • lviiii
  • 2015年01月07日 15:35
  • 709

LeetCode | Search in Rotated Sorted Array(在旋转数组中查找)

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 m...

LeetCode81——Search in Rotated Sorted Array II

LeetCode81——Search in Rotated Sorted Array II

[leetcode] 154.Find Minimum in Rotated Sorted Array II

题目: Follow up for “Find Minimum in Rotated Sorted Array”: What if duplicates are allowed?Would thi...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:#39 Recover Rotated Sorted Array
举报原因:
原因补充:

(最多只允许输入30个字)