[LeetCode]Single Number III

本文介绍了一种算法,用于在数组中找到恰好出现两次的元素,其余元素各出现两次。通过使用异或操作,可以高效地找到这两个唯一的元素,并且在常数空间复杂度下实现。

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?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

主要的问题是怎么把两个只有一个数的A和B分开。

如果全部异或的话得到的结果就是A^B。

A!=B,所以异或的结果中必然存在1,那么为1的那一位对应的A和B必然一个是1,一个是0,这个就可以将所有数字分为两类。

分别异或就能达到两个值了。

获取A,B最后不同的一位的方法是mask=AxorB & (~AxorB-1))。

 1 class Solution {
 2 public:
 3     vector<int> singleNumber(vector<int>& nums) {
 4         vector<int> result;
 5         if(nums.size()<2) return result;
 6         int AxorB = 0;
 7         for(int i=0;i<nums.size();i++)
 8         {
 9             AxorB^=nums[i];
10         }
11         int mask = AxorB & (~(AxorB-1));
12         int A=0,B=0;
13         for(int i=0;i<nums.size();i++)
14         {
15             if(mask&nums[i])
16             {
17                 A^=nums[i];
18             }
19             else
20             {
21                 B^=nums[i];
22             }
23         }
24         result.push_back(A);
25         result.push_back(B);
26         return result;
27     }
28 };

 

转载于:https://www.cnblogs.com/Sean-le/p/4787551.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值