Single Number III

来源:互联网 发布:老园丁淘宝店哪家正版 编辑:程序博客网 时间:2024/06/08 00:05

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.

  1. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity
解题技巧:

该题与Single Number、Single NumberII相似,我们可以想办法将两个只出现过一次的数字分到两个不同的小组中,然后分别调用Single Number中的方法来得到结果。具体做法是:首先我们可以将所有的数进行异或运算,这将得到两个不同的数的异或结果,然后,用 x &= -x来取出数字a的最右端为1的位,之后,与原数组中的数进行与运算,将两个不同的数字分到不同的小组中,最后分别对两个小组中的数字进行异或运算,便可以得到最终结果

代码:
#include <iostream>#include <vector>using namespace std;int XOR(vector<int>& nums){int sum = 0, len = nums.size();for (int i = 0; i < len; i++){sum = sum ^ nums[i];}return sum;}vector<int> singleNumber(vector<int>& nums) {int diff;diff = XOR(nums);diff &= -diff;vector<int> res(2, 0);for (int i = 0; i < nums.size(); i++){if (diff & nums[i]) res[0] = res[0] ^ nums[i];else res[1] = res[1] ^ nums[i];}return res;}int main(){vector<int> nums, res;int x;while (cin >> x)nums.push_back(x);res = singleNumber(nums);for (int i = 0; i < res.size(); i++)cout << res[i] << endl;system("pause");}


原创粉丝点击