From f6a326b268b3e1a0213bdff57d3fb044ce3f8b8a Mon Sep 17 00:00:00 2001 From: Heber Alturria <110596115+HeberDamianAlturria@users.noreply.github.com> Date: Thu, 23 Feb 2023 14:32:04 -0300 Subject: [PATCH] feat: add LeetCode problem 540 (#1217) * feat: add LeetCode problem 540 * feat: Added a description to the LeetCode problem 540 * feat: Added details in the description of the LeetCode problem 540 * feat: Changed a word in @details of the LeetCode problem 540 --- leetcode/DIRECTORY.md | 1 + leetcode/src/540.c | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 leetcode/src/540.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 87489a6d..a7ccca3a 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -91,6 +91,7 @@ | 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones) | [C](./src/485.c) | Easy | | 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number) | [C](./src/509.c) | Easy | | 520 | [Detect Capital](https://leetcode.com/problems/detect-capital) | [C](./src/520.c) | Easy | +| 540 | [Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/) | [C](./src/540.c) | Medium | | 561 | [Array Partition](https://leetcode.com/problems/array-partition) | [C](./src/561.c) | Easy | | 567 | [Permutation in String](https://leetcode.com/problems/permutation-in-string) | [C](./src/567.c) | Medium | | 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees) | [C](./src/617.c) | Easy | diff --git a/leetcode/src/540.c b/leetcode/src/540.c new file mode 100644 index 00000000..094bb132 --- /dev/null +++ b/leetcode/src/540.c @@ -0,0 +1,32 @@ +/** + * Time complexity: O(log n). + * Space complexity: O(1). + * @details The array has a pattern that consists in of the existing sub-array to + * the left of the non-repeating number will satisfy the condition that + * each pair of repeated elements have their first occurrence at the even index + * and their second occurrence at the odd index, and that the sub-array to + * the right of the non-repeating number will satisfy the condition that + * each pair of repeated elements have their first occurrence at the odd index + * and their second occurrence at the even index. With this pattern in mind, + * we can solve the problem using binary search. + */ + +int singleNonDuplicate(int* nums, int numsSize) { + int left = 0, right = numsSize - 1; + while (left < right) { + int mid = (right + left) / 2; + if (mid % 2 == 0) { + if (nums[mid] == nums[mid + 1]) + left = mid + 2; + else + right = mid; + } + else { + if (nums[mid] == nums[mid - 1]) + left = mid + 1; + else + right = mid - 1; + } + } + return nums[left]; +}