LeetCode 260 Single Number III 数组中除了两个数外,其他的数都出现了两次,找出这两个只出现一次的数...

本文介绍了一种线性时间复杂度和常数空间复杂度的方法来找出数组中仅出现一次的两个元素。通过两次使用异或运算,巧妙地将这两个元素分离出来。

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?

方法一:

首先计算nums数组中所有数字的异或,记为xor
令lowbit = xor & -xor,lowbit的含义为xor从低位向高位,第一个非0位所对应的数字
例如假设xor = 6(二进制:0110),则-xor为(二进制:1010,-6的补码)
则lowbit = 2(二进制:0010)

 1 class Solution {
 2 public:
 3     vector<int> singleNumber(vector<int>& nums) {
 4         int size=nums.size();
 5         if(size==0||nums.empty())
 6             return vector<int>();
 7         int diff=0;
 8         for(auto &ele:nums)
 9             diff^=ele;
10         vector<int> res(2,0);
11         diff&=-diff;//从低位向高位,第一个非0位所对应的数字
12         for(auto &ele:nums)
13             if(diff&ele)
14                 res[0]^=ele;
15             else
16                 res[1]^=ele;
17         return res;
18     }
19 };

 方法二:

 1 class Solution {
 2 public:
 3     vector<int> singleNumber(vector<int>& nums) {
 4         int size=nums.size();
 5         if(size==0||nums.empty())
 6             return vector<int>();
 7         int sum=0;
 8         for(auto &ele:nums)
 9             sum^=ele;
10         vector<int> res(2,0);
11         //从低位向高位,第一个非0位所对应的数字
12         int n=1;
13         while((sum&n)==0)
14             n=n<<1;
15         for(auto &ele:nums)
16             if(n&ele)
17                 res[0]^=ele;
18             else
19                 res[1]^=ele;
20         return res;
21     }
22 };

 

转载于:https://www.cnblogs.com/xidian2014/p/8536847.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值