diff options
author | Jack Sangdahl <[email protected]> | 2025-02-01 20:44:17 -0700 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-02-01 20:44:17 -0700 |
commit | 21d9f8ba7c8e6d1b3adc284878baca1455f48648 (patch) | |
tree | 627fed3e3fab932a527c9072906daed045d57093 | |
parent | a6a2deed1686008534328bf255c4fea92b72fd2e (diff) | |
download | leetcode-21d9f8ba7c8e6d1b3adc284878baca1455f48648.tar.gz leetcode-21d9f8ba7c8e6d1b3adc284878baca1455f48648.zip |
1752. check if array is sorted and rotated
-rw-r--r-- | check_array_sorted_rotated.c | 24 | ||||
-rw-r--r-- | check_array_sorted_rotated.py | 25 |
2 files changed, 49 insertions, 0 deletions
diff --git a/check_array_sorted_rotated.c b/check_array_sorted_rotated.c new file mode 100644 index 0000000..bf9a844 --- /dev/null +++ b/check_array_sorted_rotated.c @@ -0,0 +1,24 @@ +// 1752. Check if Array Is Sorted and Rotated +#include "leetcode.h" + +/* + * 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.len]'. + */ + +bool check(int *nums, int numsSize) { + for (int i = 0, k = 0; i < numsSize; ++i) + if (nums[i] > nums[(i + 1) % numsSize] && ++k > 1) + return false; + return true; +} + +int main() { + int n1[] = {3, 4, 5, 1, 2}, n2[] = {2, 1, 3, 4}, n3[] = {1, 2, 3}; + printf("%d\n", check(n1, ARRAY_SIZE(n1))); // expect: 1 + printf("%d\n", check(n2, ARRAY_SIZE(n2))); // expect: 0 + printf("%d\n", check(n3, ARRAY_SIZE(n3))); // expect: 1 +} diff --git a/check_array_sorted_rotated.py b/check_array_sorted_rotated.py new file mode 100644 index 0000000..8a94f1f --- /dev/null +++ b/check_array_sorted_rotated.py @@ -0,0 +1,25 @@ +# 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.len]'. +""" + + +class Solution(object): + def check(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + return sum(a > b for a, b in zip(nums, nums[1:] + nums[:1])) <= 1 + + +if __name__ == "__main__": + obj = Solution() + print(obj.check(nums=[3, 4, 5, 1, 2])) + print(obj.check(nums=[2, 1, 3, 4])) + print(obj.check(nums=[1, 2, 3])) |