|
| 1 | +/** |
| 2 | + * [1752] Check if Array Is Sorted and Rotated |
| 3 | + * |
| 4 | + * 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. |
| 5 | + * There may be duplicates in the original array. |
| 6 | + * 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. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * Input: nums = [3,4,5,1,2] |
| 11 | + * Output: true |
| 12 | + * Explanation: [1,2,3,4,5] is the original sorted array. |
| 13 | + * You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2]. |
| 14 | + * |
| 15 | + * Example 2: |
| 16 | + * |
| 17 | + * Input: nums = [2,1,3,4] |
| 18 | + * Output: false |
| 19 | + * Explanation: There is no sorted array once rotated that can make nums. |
| 20 | + * |
| 21 | + * Example 3: |
| 22 | + * |
| 23 | + * Input: nums = [1,2,3] |
| 24 | + * Output: true |
| 25 | + * Explanation: [1,2,3] is the original sorted array. |
| 26 | + * You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. |
| 27 | + * |
| 28 | + * |
| 29 | + * Constraints: |
| 30 | + * |
| 31 | + * 1 <= nums.length <= 100 |
| 32 | + * 1 <= nums[i] <= 100 |
| 33 | + * |
| 34 | + */ |
| 35 | +pub struct Solution {} |
| 36 | + |
| 37 | +// problem: https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/ |
| 38 | +// discuss: https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/?currentPage=1&orderBy=most_votes&query= |
| 39 | + |
| 40 | +// submission codes start here |
| 41 | + |
| 42 | +impl Solution { |
| 43 | + pub fn check(nums: Vec<i32>) -> bool { |
| 44 | + let mut count = 0; |
| 45 | + |
| 46 | + for (i, v) in nums.iter().enumerate() { |
| 47 | + if v > &nums[(i + 1) % nums.len()] { |
| 48 | + count += 1; |
| 49 | + } |
| 50 | + if count > 1 { |
| 51 | + return false; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + true |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +// submission codes end |
| 60 | + |
| 61 | +#[cfg(test)] |
| 62 | +mod tests { |
| 63 | + use super::*; |
| 64 | + |
| 65 | + #[test] |
| 66 | + fn test_1752_example_1() { |
| 67 | + let nums = vec![3, 4, 5, 1, 2]; |
| 68 | + |
| 69 | + let result = true; |
| 70 | + |
| 71 | + assert_eq!(Solution::check(nums), result); |
| 72 | + } |
| 73 | + |
| 74 | + #[test] |
| 75 | + fn test_1752_example_2() { |
| 76 | + let nums = vec![2, 1, 3, 4]; |
| 77 | + |
| 78 | + let result = false; |
| 79 | + |
| 80 | + assert_eq!(Solution::check(nums), result); |
| 81 | + } |
| 82 | + |
| 83 | + #[test] |
| 84 | + fn test_1752_example_3() { |
| 85 | + let nums = vec![1, 2, 3]; |
| 86 | + |
| 87 | + let result = true; |
| 88 | + |
| 89 | + assert_eq!(Solution::check(nums), result); |
| 90 | + } |
| 91 | +} |
0 commit comments