Recover Rotated Sorted Array
2015-08-05 15:49
330 查看
Given a rotated sorted array, recover it to sorted array in-place.
Have you met this question in a real interview?
Yes
Example
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]
此题目的意思,是说给定一个已经旋转过的数组,然后恢复为未旋转之前的数组;为了恢复,首先得知道数组旋转了多少次,所以先统计数组旋转的次数K,那么K之前是递增的,K之后也是递增的,如何恢复呢?这里巧妙的用到了反转,可以先将K之前的部分反转一次,然后K之后的部分反转一次,最后再全部反转一次,这样会发现,得到的数组,刚好是未旋转之前的数组。时间复杂度刚好为O(2 * N),空间复杂度为O(1).。
Have you met this question in a real interview?
Yes
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]
此题目的意思,是说给定一个已经旋转过的数组,然后恢复为未旋转之前的数组;为了恢复,首先得知道数组旋转了多少次,所以先统计数组旋转的次数K,那么K之前是递增的,K之后也是递增的,如何恢复呢?这里巧妙的用到了反转,可以先将K之前的部分反转一次,然后K之后的部分反转一次,最后再全部反转一次,这样会发现,得到的数组,刚好是未旋转之前的数组。时间复杂度刚好为O(2 * N),空间复杂度为O(1).。
class Solution { public: //找到最小值的下标,然后恢复原始数组顺序 //恢复的时候,用反转,先整个反转一次,然后,每段分开反转一次 void Swap(int &a, int &b) { a = a + b; b = a - b; a = a - b; } void recoverRotatedSortedArray(vector<int> &nums) { // write your code here int len = nums.size(); if(len < 2) return; int k = 0; for(int i = 1; i < len; ++i) { if(nums[i] < nums[i - 1]) { k = i; break; } } if(k == 0) return; //第一次反转前面部分 int low = 0, high = k - 1; while(low < high) { Swap(nums[low], nums[high]); ++low; --high; } //第二次反转后面部分 low = k; high = len - 1; while(low < high) { Swap(nums[low], nums[high]); ++low; --high; } //反转整个数组 low = 0; high = len - 1; while(low < high) { Swap(nums[low], nums[high]); ++low; --high; } } };
相关文章推荐
- Linux Shell - 如何使用sort与uniq命令删除重复的文本行
- Redis sort 排序命令详解
- dos下用recover修复损坏的TXT文件
- 批处理命令教学之字符串排序(sort)
- C++ 关于STL中sort()对struct排序的方法
- Js中sort()方法的用法
- 如何写JS数组sort的比较函数
- javascript中sort()的用法实例分析
- js模拟实现Array的sort方法
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- js表数据排序 sort table data
- javascript 数组排序函数sort和reverse使用介绍
- JavaScript Table排序 2.0 (更新)
- js中数组(Array)的排序(sort)注意事项说明
- Javascript数组的排序 sort()方法和reverse()方法
- Java数据结构及算法实例:插入排序 Insertion Sort
- Java数据结构及算法实例:选择排序 Selection Sort
- php-redis中的sort排序函数总结
- php通过sort()函数给数组排序的方法
- Lua的table库函数insert、remove、concat、sort详细介绍