Given an array num, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.
There may be duplicates in the original array.
Note: An array A
rotated by x
positions result in an array B
of the same length such that A[i] == B[(i+x) % A.length]
, where %
is the modulo operation.
Example:
Input: nums = [3,4,5,1,2]
Output: true
Explanation: [1,2,3,4,5] is the original sorted array.
You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].
Approach:
C++
#include <bits/stdc++.h>using namespace std;bool check(vector<int> &nums){//find position of minimum elementint k = min_element(nums.begin(), nums.end()) - nums.begin();//length of arrayint n = nums.size();int j;if (k == 0){j = n - 1;while (j > 0 && nums[j] == nums[k]){j--;}}else{j = k - 1;}int i = k;while (i != j){if (nums[i] > nums[(i + 1) % n]){return false;}i = (i + 1) % n;}return true;}int main(){vector<int> nums = {3, 4, 5, 1, 2};if (check(nums))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment