Leetcode: Single Number II

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)的?通过扫描几遍数组就可以的?




你可能感兴趣的:(LeetCode,number,single)