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.
Example:
Input:[1,2,1,3,2,5]
Output:[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
题目大意:
给定数组中只有两个元素只出现一次,其余元素均出现两次,找到这两个元素。
要求算法具备线性时间复杂度。
理 解:
已知异或运算,两数相同异或为0。则将数组所有数异或的结果即为两不同元素异或的结果,选取非0的最低位,两个元素在该位一定有个数为1,有个数为0.
根据该非0位划分,将数组分为两部分,则两部分异或的结果即为两个不同的元素。
代 码 C++:
class Solution { public: vector<int> singleNumber(vector<int>& nums) { int len = nums.size(); vector<int> res; if(len==2){ res.push_back(nums[0]); res.push_back(nums[1]); } if(len<=3 || len&1==1) return res; int xor1=0; for(int i=0;i<len;++i){ xor1 = xor1^nums[i]; } int index = 1; while(xor1!=0){ if(xor1&1==1){ break; } xor1 = xor1 >> 1; index++; } int xor2=0,xor3=0; int isOne=1; while(index>1){ isOne = isOne*2; index--; } for(int i=0;i<len;++i){ int flag = nums[i]&isOne; if(flag==0){ xor2 = xor2^nums[i]; } else{ xor3 = xor3^nums[i]; } } res.push_back(xor2); res.push_back(xor3); return res; } };
leetcode [260] - Single Number III
原文:https://www.cnblogs.com/lpomeloz/p/10922131.html