题目来源: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 }
时间: 2024-10-12 14:02:12