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.

Example 1:

Input: nums ={3,3,7,7,10,11,11}
Output: 10

Approach

Java


public class SingleElementSortedArray {
    public static void main(String[] args) {
        int nums[] = { 3377101111 };
        System.out.println(singleNonDuplicate(nums));
    }

    private static int singleNonDuplicate(int[] nums) {
        int res = 0;
        for (int i = 0; i < nums.length; i++)
            res ^= nums[i];
        return res;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;


int singleNonDuplicate(vector<int>& nums
{
     int res=0;
      for(int i=0;i<nums.size();i++)
            res^=nums[i];
     return res;
}

int main()
{
    vector<intnums={3,3,7,7,10,11,11};
    cout<<singleNonDuplicate(nums);
    return 0;
}


No comments:

Post a Comment