Forked from SuryaPratapK/Single Element in a Sorted Array
Created
May 15, 2020 18:36
-
-
Save SAgarwal-24/5b9979d7a4d5889684ca813a85c224d0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| int singleNonDuplicate(vector<int>& nums) { | |
| ios_base::sync_with_stdio(false); | |
| cin.tie(NULL); | |
| int high = nums.size()-1; | |
| int low = 0; | |
| int mid; | |
| //Boundary cases | |
| if(high==0) | |
| return nums[0]; | |
| else if(nums[0]!=nums[1]) | |
| return nums[0]; | |
| else if(nums[high]!=nums[high-1]) | |
| return nums[high]; | |
| while(low<=high) | |
| { | |
| mid = low + (high-low)/2; | |
| //Unique element condition | |
| if(nums[mid]!=nums[mid+1] && nums[mid]!=nums[mid-1]) | |
| return nums[mid]; | |
| if(((mid%2)==0 && nums[mid]==nums[mid+1]) | |
| || ((mid%2)==1 && nums[mid]==nums[mid-1])) | |
| low = mid+1; | |
| else | |
| high = mid-1; | |
| } | |
| return -1; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment