#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(33). Search in Rotated Sorted Array

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

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

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

leetcode——Find Minimum in Rotated Sorted Array II

题目一: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5...

LeetCode Solutions : Find Minimum in Rotated Sorted Array

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

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...

153. Find Minimum in Rotated Sorted Array\229. Majority Element II\Moore's voting algorithm

Find Minimum in Rotated Sorted Array 题目描述 代码实现153. Find Minimum in Rotated Sorted Array题目描述一个已经排好序的数...

Leetcode 153. Find Minimum in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.(i.e.,...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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