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
This commit is contained in:
Heber Alturria 2023-02-23 14:32:04 -03:00 committed by GitHub
parent 5d3a841aa6
commit f6a326b268
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 0 deletions

View File

@ -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 |

32
leetcode/src/540.c Normal file
View File

@ -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];
}