Violence
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public boolean check(int[] nums) { int n = nums.length;
int[] clonedNums = nums.clone(); Arrays.sort(clonedNums);
for (int rotateTimes = 0; rotateTimes < n; rotateTimes++) { if (arrayEquals(nums, clonedNums, rotateTimes)) { return true; } }
return false; }
private boolean arrayEquals(int[] nums, int[] clonedNums, int rotateTimes) { for (int i = 0; i < nums.length; i++) { if (nums[i] != clonedNums[safeIndex(i + rotateTimes, nums.length)]) { return false; } }
return true; }
private int safeIndex(int index, int n) { return index % n; } }
|
Traverse
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public boolean check(int[] nums) {
boolean decrease = false;
for (int i = 1; i < nums.length; i++) { if (nums[i] < nums[i - 1]) { if (!decrease) { decrease = true; } else { return false; } } }
if (decrease) { return nums[nums.length - 1] <= nums[0]; } else { return true; } } }
|
References
1752. Check if Array Is Sorted and Rotated