Repository containing solution for #SdeSheetChallenge by striver
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return the single element that appears only once.
Your solution must run in O(log n)
time and O(1)
space.
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int ans = 0;
for(auto x:nums) ans^=x;
return ans;
}
};
class Solution {
public:
int singleNonDuplicate(vector<int>& nums)
{
int low = 0, high = nums.size() - 2;
while (low <= high) {
int mid = (low + high) >> 1;
if (nums[mid] == nums[mid ^ 1]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return nums[low];
}
};
[[C++] 7 Simple Solutions w/ Explanation | Brute + Hashmap + XOR + Linear + 2 Binary Search](https://leetcode.com/problems/single-element-in-a-sorted-array/discuss/1587270/C%2B%2B-5-Simple-Solutions-w-Explanation-or-Hashmap-%2B-XOR-%2B-Linear-Search-%2B-Binary-Search) |