1752. Check if Array Is Sorted and Rotated #1260
-
Topics: Given an array There may be duplicates in the original array. Note: An array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if the given array can be obtained by rotating a sorted array in non-decreasing order. Here's a step-by-step approach to achieve this:
Let's implement this solution in PHP: 1752. Check if Array Is Sorted and Rotated <?php
function check($nums) {
$n = count($nums);
$pivot = -1;
// Find the pivot where the order drops
for ($i = 0; $i < $n - 1; $i++) {
if ($nums[$i] > $nums[$i + 1]) {
$pivot = $i + 1;
break;
}
}
// If no pivot found, the array is already sorted
if ($pivot == -1) {
return true;
}
// Check if the array is sorted after the pivot
for ($i = $pivot; $i < $n - 1; $i++) {
if ($nums[$i] > $nums[$i + 1]) {
return false;
}
}
// Check if the last element is less than or equal to the first element
if ($nums[$n - 1] > $nums[0]) {
return false;
}
return true;
}
// Test cases
$nums1 = [3,4,5,1,2];
$nums2 = [2,1,3,4];
$nums3 = [1,2,3];
var_dump(check($nums1)); // Output: bool(true)
var_dump(check($nums2)); // Output: bool(false)
var_dump(check($nums3)); // Output: bool(true)
?> Explanation:
Complexity:
This approach ensures that we correctly identify if the array can be obtained by rotating a sorted array. |
Beta Was this translation helpful? Give feedback.
We need to determine if the given array can be obtained by rotating a sorted array in non-decreasing order. Here's a step-by-step approach to achieve this:
Check if the array is already sorted: If the array is already sorted, it means it can be rotated 0 positions to get the same array, so we should return
true
.Find the pivot point: The pivot point is where the order drops, i.e., where
nums[i] > nums[i+1]
. This pivot point indicates the rotation point.Check the order: After finding the pivot, we need to ensure that the array is sorted in non-decreasing order before and after the pivot.
Handle duplicates: If there are duplicates, we need to ensure that the pivot is the only point…