lintcode Recover Rotated Sorted Array
2015-08-03 17:31
441 查看
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]
zh找到轴点,分别交换三次
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]
zh找到轴点,分别交换三次
class Solution { public: void recoverRotatedSortedArray(vector<int> &nums) { // write your code here int len = nums.size(); if (0 == len) { return ; } int t = 0; for (int i = 0; i < len; ++i) { if (nums[i] < nums[t] ) { t = i; } } reverse(nums,0,t-1); reverse(nums,t,len-1); reverse(nums,0,len-1); } void reverse(vector<int> &nums,int lo,int hi) { while (lo<hi) { swap(nums[lo],nums[hi]); ++lo; --hi; } } };
相关文章推荐
- WebX5 Data判断当前行的值是否改变,以及改变当前行的状态
- POJ 2492 A Bug's Life (并查集)
- 内部类中class声明地方不同,效果不一样
- 自定义 Spring Security 4 的UserDetailsService和UserDetails
- 1.9-selinux介绍
- easyui-accordion动态生成菜单的实现
- 如何实现一个checkbox选择框
- Mysql_存储功能
- magento的url中 去掉多余的目录层级
- IO重定向 > >> <
- UVa 1511 - Soju
- 2.2&2.3 Variables
- CSS3中的clip-path使用攻略
- 内存(堆)的动态申请和释放
- 1.8-抓包工具tcpdump和tshark
- PHP中try{}catch{}的具体用法详解
- leetcode-232-Implement Queue using Stacks
- 内存(堆)的动态申请和释放
- 哎哟,不错哦之玩乐动物园
- 用C语言写猜数字游戏