class Solution:
def check(self, nums):
count = 0
n = len(nums)
for i in range(n):
if nums[i] > nums[(i + 1) % n]:
count += 1
if count > 1:
return False
return True
class Solution {
public:
bool check(vector<int>& nums) {
int count = 0, n = nums.size();
for (int i = 0; i < n; ++i) {
if (nums[i] > nums[(i + 1) % n]) {
count++;
}
if (count > 1) return false;
}
return true;
}
};
class Solution {
public boolean check(int[] nums) {
int count = 0, n = nums.length;
for (int i = 0; i < n; i++) {
if (nums[i] > nums[(i + 1) % n]) {
count++;
}
if (count > 1) return false;
}
return true;
}
}
var check = function(nums) {
let count = 0, n = nums.length;
for (let i = 0; i < n; i++) {
if (nums[i] > nums[(i + 1) % n]) {
count++;
}
if (count > 1) return false;
}
return true;
};
You are given an array of integers nums. The task is to determine whether nums could become a non-decreasingly sorted array if it were rotated some number of times (possibly zero). In a rotation, the array is split into two parts and swapped, so the order is preserved but the starting point is changed.
The key constraints are:
[3,4,5,1,2] can be rotated to [1,2,3,4,5] (sorted), but [2,1,3,4] cannot be rotated to a sorted array.
To solve this problem, let's first understand what it means for an array to be sorted and rotated:
The key insight: if there is more than one "drop" in the array, it cannot be rotated into a sorted array.
Let's break down the steps:
count) to zero. This will track how many times an element is greater than its next element.i, compare nums[i] with nums[(i+1) % n] (using modulo to wrap around to the first element at the end).nums[i] > nums[(i+1) % n], increment count.count ever becomes greater than 1, return False (the array cannot be rotated to sorted).count is 0 or 1, return True.This works because:
Let's walk through an example with nums = [3, 4, 5, 1, 2]:
True.
Another example: nums = [2, 1, 3, 4]
False.
Brute-force approach:
The optimized solution is much more efficient, especially for large arrays.
This problem is elegantly solved by recognizing that a sorted and rotated array can have at most one "drop" in order. By counting these drops in a single pass, we avoid brute-force rotations and achieve an efficient O(n) time, O(1) space solution. The key insight is that the structure of a sorted and rotated array is simple and can be checked directly without actual rotation.