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:
- The order of the result is not important. So in the above example,
[5, 3]
is also correct.- Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
题目很简单,但是通过这个题目让我见识了LeetCode众多大牛的存在。
代码中,第一次了使用accumulate函数,然后还要bit_xor<int>()之类的C++11的function object。
此处如果diff = INT_MIN, 那么 -diff 恰好会溢出到 INT_MIN. 之前并没有注意过这个问题。
1 class Solution { 2 public: 3 vector<int> singleNumber(vector<int>& nums) { 4 int diff = accumulate(begin(nums), end(nums), 0, bit_xor<int>()); 5 diff &= -diff; 6 vector<int> result = {0, 0}; 7 for (auto num: nums) { 8 result[!(diff & num)] ^= num; 9 } 10 return result; 11 } 12 };