1752. Check if Array Is Sorted and Rotated

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]; // 注意此处是小于等于,如数组:[6, 10, 6]
} else {
return true;
}
}
}

References

1752. Check if Array Is Sorted and Rotated