码迷,mamicode.com
首页 > 其他好文 > 详细

Recover Rotated Sorted Array

时间:2015-09-03 06:59:24      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

Given a rotated sorted array, recover it to sorted array in-place.

 

Have you met this question in a real interview?

Yes
Which company asked you this question? Airbnb Alibaba Amazon Apple Baidu Bloomberg Cisco Dropbox Ebay Facebook Google Hulu Intel Linkedin Microsoft NetEase Nvidia Oracle Pinterest Snapchat Tencent Twitter Uber Xiaomi Yahoo Yelp Zenefits
Thanks for your feedback.
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]

 

 

 

 

 1     public void recoverRotatedSortedArray(ArrayList<Integer> nums) 
 2     {
 3         // write your code
 4         if(nums.size()==0||nums.size()==1) return;
 5         int i =0;
 6         for(i=0; i<nums.size()-1;i++)
 7         {
 8             if(nums.get(i)>nums.get(i+1)) 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         return;
15         
16         
17     }
18     
19     
20     public void reverse(ArrayList<Integer> nums, int left, int right)
21     {
22         while(left<right)
23         {
24             int temp = nums.get(left);
25             nums.set(left,nums.get(right));
26             nums.set(right,temp);
27             left++;
28             right--;
29         
30         }
31       
32         return;
33     }

 

Recover Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4779854.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!