1752. Check if Array Is Sorted and Rotated
#array
Intuition
[1,2,3,4,5,6,7,8,9] => rotate clockwise 3 time => [7,8,9,1,2,3,4,5,6]
[1,2,3,4,5,6,7,8,9] => rotate anti-clockwise 3 time => [4,5,6,7,8,9,1,2,3]Complexity
Space Complexity
Time Complexity
Code
public boolean check(int[] nums) {
// if the array is sorted the next immediate will always be larger
// except at the point of rotation
int countInversion = 0;
for (int i = 0; i < nums.length; ++i) {
if( nums[i] > nums[ (i+1)%nums.length ] ) countInversion++;
}
return countInversion <= 1 ;
}Last updated