[LeetCode] 1752. Check if Array Is Sorted and Rotated
Given an array nums
, return true
if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false
.
There may be duplicates in the original array.
Note: An array A
rotated by x
positions results in an array B
of the same length such that A[i] == B[(i+x) % A.length]
, where %
is the modulo operation.
Example 1:
Input: nums = [3,4,5,1,2] Output: true Explanation: [1,2,3,4,5] is the original sorted array. You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].
Example 2:
Input: nums = [2,1,3,4] Output: false Explanation: There is no sorted array once rotated that can make nums.
Example 3:
Input: nums = [1,2,3] Output: true Explanation: [1,2,3] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
检查数组是否经排序和轮转得到。
给你一个数组 nums 。nums 的源数组中,所有元素与 nums 相同,但按非递减顺序排列。
如果 nums 能够由源数组轮转若干位置(包括 0 个位置)得到,则返回 true ;否则,返回 false 。
源数组中可能存在 重复项 。
注意:我们称数组 A 在轮转 x 个位置后得到长度相同的数组 B ,当它们满足 A[i] == B[(i+x) % A.length] ,其中 % 为取余运算。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/check-if-array-is-sorted-and-rotated
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题考察的是数组的轮转问题。input 给的是一个数组,请你判断这个数组是否是由某个数组轮转过若干步得来的。如果是的话,因为原数组是从左往右单调增(起码是非递减),所以轮转过的数组只能有一处满足 nums[i] > nums[i + 1]。所以做法就是对 input 数组遍历,记录 nums[i] > nums[i + 1] 是否只出现过一次。如果出现超过一次,就返回false。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public boolean check(int[] nums) { 3 int len = nums.length; 4 // corner case 5 if (len <= 1) { 6 return true; 7 } 8 9 // normal case 10 int count = 0; 11 for (int i = 0; i < len; i++) { 12 if (nums[i] > nums[(i + 1) % len]) { 13 count++; 14 } 15 } 16 return count <= 1 ? true : false; 17 } 18 }