Skip to content

Commit

Permalink
Sync LeetCode submission - Single Element in a Sorted Array (cpp)
Browse files Browse the repository at this point in the history
  • Loading branch information
pradeeptosarkar committed Sep 15, 2023
1 parent f4c30a0 commit b2259c6
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions LeetCode/problems/single_element_in_a_sorted_array/solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
public:
int singleNonDuplicate(vector<int>& nums)
{
int n=nums.size();
if(n==1 or nums[0]!=nums[1]) return nums[0];
if(nums[n-2]!=nums[n-1]) return nums[n-1];

int left=0, right=n-1;

int mid;

while(left<=right)
{
mid = (left+right)/2;
if(nums[mid]!=nums[mid-1] and nums[mid]!=nums[mid+1])
return nums[mid];

else if(mid%2==0 and nums[mid]==nums[mid+1] or (mid%2==1 and nums[mid]==nums[mid-1]))
left=mid+1;

else
right=mid-1;
}

return -1;
}
};

0 comments on commit b2259c6

Please sign in to comment.