Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once.
The expected time complexity is O(n) and O(1) extra space.
Example:
Input: arr[]={2,3,3,4,4,3,4} Output: 2
Approach
C++
#include <bits/stdc++.h>using namespace std;int findNumberAppearsOnce(vector<int> &nums){int first = 0, second = 0, third;int n = nums.size();//iterate till the end of arrayfor (int i = 0; i < n; i++){//update secondsecond = second | (first & nums[i]);//update firstfirst = first ^ nums[i];//update thirdthird = ~(first & second);//update firstfirst = first & third;second = second & third;}return first;}int main(){vector<int> nums = {2, 3, 3, 4, 4, 3, 4};cout << findNumberAppearsOnce(nums);return 0;}
No comments:
Post a Comment