码迷,mamicode.com
首页 > 编程语言 > 详细

[容易]恢复旋转排序数组

时间:2016-05-04 17:21:41      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:http://www.lintcode.com/zh-cn/problem/recover-rotated-sorted-array/

技术分享

可以accept的程序如下:

1 class Solution {
2 public:
3     void recoverRotatedSortedArray(vector<int> &nums) {
4         // write your code here
5         sort(nums.begin(),nums.end());
6     }
7 };

可以accept的程序2:

 1 class Solution {
 2 public:
 3     int getGCD(int a, int b) {
 4         if (a % b == 0) {
 5             return b;
 6         }    
 7         return getGCD(b, a % b);
 8     }
 9     
10     void recoverRotatedSortedArray(vector<int> &nums) {
11         int offset = 0;
12         for (int i = 1; i < nums.size(); i++) {
13             if (nums[i - 1] > nums[i]) {
14                 offset = i;
15             }
16         }
17         if (offset == 0) {
18             return;
19         }
20         offset = nums.size() - offset;
21         
22         int gcd = getGCD(offset, nums.size());
23         for (int i = 0; i < gcd; i++) {
24             int next = (i + offset) % nums.size();
25             while (next != i) {
26                 int temp = nums[i]; nums[i] = nums[next]; nums[next] = temp;
27                 next = (next + offset) % nums.size();
28             }
29         }
30     }
31 };

完整的测试程序如下:

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     void recoverRotatedSortedArray(vector<int> &nums) {
 9         // write your code here
10         sort(nums.begin(),nums.end());
11     }
12 };
13 
14 int main()
15 {
16     Solution solu;
17     vector<int> n;
18     n.push_back(4);
19     n.push_back(5);
20     n.push_back(1);
21     n.push_back(2);
22     n.push_back(3);
23     solu.recoverRotatedSortedArray(n);
24     for(int i=0;i<n.size();i++)
25         cout<<n.at(i)<<" ";
26 }

[容易]恢复旋转排序数组

标签:

原文地址:http://www.cnblogs.com/hslzju/p/5459000.html

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