1752: Check-if-Array-Is-Sorted-and-Rotated
Easy
Simple algorithm; just have to keep track of how many times
nums[i] < nums[i-1]
and make sure that the
number of occurences is less than or equal to
1 (also remember to compare
nums[0] < nums[nums.size()-1]
)
Code:
class Solution {
public:
bool check(vector<int>& nums) {
int count = 1;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] < nums[i-1]) {
--count;
if (count < 0) {
return false;
}
}
}
if (nums[0] < nums[nums.size()-1]) {
--count;
if (count < 0) {
return false;
}
}
return true;
}
};