返回介绍

solution / 1700-1799 / 1752.Check if Array Is Sorted and Rotated / README_EN

发布于 2024-06-17 01:03:14 字数 3692 浏览 0 评论 0 收藏 0

1752. Check if Array Is Sorted and Rotated

中文文档

Description

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

Solutions

Solution 1

class Solution:
  def check(self, nums: List[int]) -> bool:
    return sum(nums[i - 1] > v for i, v in enumerate(nums)) <= 1
class Solution {
  public boolean check(int[] nums) {
    int cnt = 0;
    for (int i = 0, n = nums.length; i < n; ++i) {
      if (nums[i] > nums[(i + 1) % n]) {
        ++cnt;
      }
    }
    return cnt <= 1;
  }
}
class Solution {
public:
  bool check(vector<int>& nums) {
    int cnt = 0;
    for (int i = 0, n = nums.size(); i < n; ++i) {
      cnt += nums[i] > (nums[(i + 1) % n]);
    }
    return cnt <= 1;
  }
};
func check(nums []int) bool {
  cnt := 0
  for i, v := range nums {
    if v > nums[(i+1)%len(nums)] {
      cnt++
    }
  }
  return cnt <= 1
}
function check(nums: number[]): boolean {
  const n = nums.length;
  return nums.reduce((r, v, i) => r + (v > nums[(i + 1) % n] ? 1 : 0), 0) <= 1;
}
impl Solution {
  pub fn check(nums: Vec<i32>) -> bool {
    let n = nums.len();
    let mut count = 0;
    for i in 0..n {
      if nums[i] > nums[(i + 1) % n] {
        count += 1;
      }
    }
    count <= 1
  }
}
bool check(int* nums, int numsSize) {
  int count = 0;
  for (int i = 0; i < numsSize; i++) {
    if (nums[i] > nums[(i + 1) % numsSize]) {
      count++;
    }
  }
  return count <= 1;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文