Leetcode 1752. Check if Array Is Sorted and Rotated

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Check if Array Is Sorted and Rotated

2. Solution

解析:Version 1,如果是一个非递减数组,比较每一个nums[i]nums[i+1],如果出现超过一次nums[i]>nums[i+1],则其不是一个有序的非递减数组,由于要考虑循环问题,因此要比较nums的开头和结尾元素。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
class Solution:
def check(self, nums: List[int]) -> bool:
n = len(nums)
nums.append(nums[0])
count = 0
for i in range(n):
if nums[i] > nums[i+1]:
count += 1
if count > 1:
return False
return True

Reference

  1. https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/
如果有收获,可以请我喝杯咖啡!