Given an array of integers, where all elements but one occur twice, find the unique element.
Example:
Input: a ={0,0,1,2,1}
Output: 2
Approach (Using Xor Method).
Java
public class LonelyInteger {public static void main(String[] args) {int[] a = { 0, 0, 1, 2, 1 };System.out.println(lonelyinteger(a));}static int lonelyinteger(int[] a) {int res = a[0];for (int i = 1; i < a.length; i++)res = res ^ a[i];return res;}}
C++
#include <bits/stdc++.h>using namespace std;int lonelyinteger(vector<int> a){int res = a[0];for (int i = 1; i < a.size(); i++)res = res ^ a[i];return res;}int main(){vector<int> a = {0, 0, 1, 2, 1};cout << lonelyinteger(a);return 0;}
No comments:
Post a Comment