Single Number II @LeetCode
PROBLEM :
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
class Solution {
public:
int singleNumber(vector<int>& nums) {
if(nums.size()==1)
return nums[0] ;
int result=0 ;
for(int i=0;i<32;i++){
int count=0 ;
int temp ;
temp=(1<<i) ;
for(int j=0;j<nums.size();j++)
if(nums[j]&temp)
count++ ;
if(count%3)
result=result|temp ;
}
return result ;
}
};
---------------------------------------------------------------------------------
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
class Solution {
public:
int singleNumber(vector<int>& nums) {
if(nums.size()==1)
return nums[0] ;
int result=0 ;
for(int i=0;i<32;i++){
int count=0 ;
int temp ;
temp=(1<<i) ;
for(int j=0;j<nums.size();j++)
if(nums[j]&temp)
count++ ;
if(count%3)
result=result|temp ;
}
return result ;
}
};
---------------------------------------------------------------------------------
Comments
Post a Comment