Question:
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?
Answer:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int i=0;
if(nums.size()==1)
return nums[i];
if(nums.size()==2)
return NULL;
if(nums.size()==3)
return NULL;
sort(nums.begin(), nums.end());
for(i==0;i<nums.size();i=i+3)
{
if(nums[i]!=nums[i+1])
return nums[i];
}
}
};
run code results:
Your input
[1 1 0 1 9 8 0 8 9 0 9 8 4 7 5 7 5 7 5]
Your answer
4
Expected answer
4