Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once.
if(n<1 || n%3 != 1) return -1;
map<int,int> mp;
map<int,int>::iterator it;
for(int i =0; i< n; i++)
{
it = mp.find(A[i]);
if(it == mp.end())
mp[A[i]] = 1;
else
mp[A[i]] += 1;
}
for(it = mp.begin(); it != mp.end(); it++)
if((*it).second != 3)return (*it).first;
}
这样的话就是感觉还可以了,但是有没有更简单的算法呢?比如O(n)的?通过扫描几遍数组就可以的?

本文介绍了一种算法,该算法能在给定的整数数组中找到仅出现一次的整数,而其他元素均出现了三次。算法要求线性运行时间复杂度且尽量不使用额外内存。
610

被折叠的 条评论
为什么被折叠?



