Single Number III

Description:

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:
  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

Solution:

class Solution {
public:
	vector<int> singleNumber(vector<int>& nums) {
		assert(nums.size() >= 2);
		int a = 0;
		for (auto n : nums) a ^= n;
		int nbit = (a&(a-1))^a;
		int b = 0;
		for (auto n : nums) if (n & nbit) b ^= n;
		return vector<int>({b, a^b});
	}
};
posted @ 2015-08-26 04:05  影湛  阅读(76)  评论(0编辑  收藏  举报