leetcode: Single Number (II)

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

思路

想不出来怎么做。只能数数了。
class Solution {
public:
    int singleNumber(int A[], int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
		if(n<=0 || n%2==0) return -1;
		map<int,int> num;
		for(int i=0;i<n;i++)
		{
			num[A[i]]++;
		}
		map<int,int>::iterator iter=num.begin();
        for(iter=num.begin();iter!=num.end();iter++)
		{
			if(iter->second==1) return iter->first;
		}
		return -1;
    }
};

后来参考了 Single Number II,终于懂了。不过这么巧妙的方法是那么容易想出来的么?真是在面试的时候应该看重的还是怎么去解决它吧,不过我也不知道怎么去解决它。
class Solution {
public:
    int singleNumber(int A[], int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
		if(n<=0 || n%2==0) return -1;
		int numBins[32]={0};
		int res=0;
		for(int i=0;i<32;i++)
		{
			for(int j=0;j<n;j++)
			{
				if(((A[j]>>i)&1)==1)
					numBins[i]++;
			}
			res|=(numBins[i]%2)<<i;
		}
		return res;
    }
};



你可能感兴趣的:(LeetCode,Algorithm,C++)