解法一:
利用辅助数组
class Solution {
public:
/**
* @param nums: An integer array
* @return: nothing
*/
void recoverRotatedSortedArray(vector<int> &nums) {
// write your code here
int index = 0;
int cur = 0;
for(int i = 1; i < nums.size(); i++){
if(nums[i] < nums[i-1]){
index = i;
}
}
int left;
int right;
left = 0, right = index - 1;
while(right >= left){
int tmp = nums[left];
nums[left++] = nums[right];
nums[right--] = tmp;
}
left = index, right = nums.size() - 1;
while(right >= left){
int tmp = nums[left];
nums[left++] = nums[right];
nums[right--] = tmp;
}
left = 0, right = nums.size() - 1;
while(right >= left){
int tmp = nums[left];
nums[left++] = nums[right];
nums[right--] = tmp;
}
}
};
解法2:利用一个额外的数组即可得出答案。
class Solution {
public:
/*
* @param nums: Given an integers array A
* @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
*/
vector<long long> productExcludeItself(vector<int> &nums) {
// write your code here
vector<long long> result(nums.size(), 1);
for(int i = 1; i < nums.size(); i++){
result[i] = result[i - 1] * nums[i - 1];
}
long long temp = 1;
for(int i = nums.size() - 1; i >= 0; i--){
result[i] *= temp;
temp *= nums[i];
}
return result;
}
};