aboutsummaryrefslogtreecommitdiff
path: root/other/single_element_sorted_arr.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/single_element_sorted_arr.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/single_element_sorted_arr.cpp')
-rw-r--r--other/single_element_sorted_arr.cpp33
1 files changed, 33 insertions, 0 deletions
diff --git a/other/single_element_sorted_arr.cpp b/other/single_element_sorted_arr.cpp
new file mode 100644
index 0000000..e9bd894
--- /dev/null
+++ b/other/single_element_sorted_arr.cpp
@@ -0,0 +1,33 @@
+// 540. Single Element in a Sorted Array
+#include "leetcode.h"
+
+/*
+ * given a sorted array consisting of only integers where very element appears
+ * exactly twice, except for one element which appears exactly once. return the
+ * single element that appears only once. solution func must be o(ln) time and
+ * o(1) space complexity.
+ */
+
+class Solution {
+public:
+ int singleNonDuplicate(vector<int> &nums) {
+ int low = 0, high = nums.size() - 1, mid;
+ while (low < high) {
+ mid = (low + high) / 2;
+ if ((mid % 2 && nums[mid - 1] == nums[mid]) ||
+ (!(mid % 2) && nums[mid] == nums[mid + 1]))
+ low = mid + 1;
+ else
+ high = mid;
+ }
+ return nums[low];
+ }
+};
+
+int main() {
+ Solution obj;
+ vector<int> nums1 = {1, 1, 2, 3, 3, 4, 4, 8, 8},
+ nums2 = {3, 3, 7, 7, 10, 11, 11};
+ cout << obj.singleNonDuplicate(nums1) << endl; // expect: 2
+ cout << obj.singleNonDuplicate(nums2) << endl; // expect: 10
+}