Single Element in a Sorted Array - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Wednesday, 12 August 2020

Single Element in a Sorted Array

Single Element in a Sorted Array

 

 Single Element in a Sorted Array

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.

Follow up: Your solution should run in O(log n) time and O(1) space.

 

Example 1:

Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2

Example 2:

Input: nums = [3,3,7,7,10,11,11]
Output: 10

 

 

class Solution {
public:
    int singleNonDuplicate(vector<int>& nums) {
        int l=0,h=nums.size()-1,ans;
        if(nums.size()==1)return nums[0];
        while(l<=h)
        {
            int mid=(l+h)/2;
            if(nums[l]==nums[l+1])
            {
               l+=2;
            }else{
                ans=nums[l];
                break;
            }
            if(nums[h]==nums[h-1])
            {
                h-=2;
            }else{
                ans=nums[h];
                break;
            }
        }
        return ans;
        
    }
};