260. Single Number III
来源:互联网 发布:公司注册淘宝店 编辑:程序博客网 时间:2024/06/04 19:00
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?
1. 第一个pass: 把数组里面所有的数都xor起来,会得到单独的两个数的xor结果,相同的元素xor结果是0,和0 xor的结果是这个数本身,因为单独的两个数彼此之间是不相同的,所以一定有一些数位上的数是不同的,xor的结果这位上就是1.
xor = ~(xor - 1) 能够找到两个数里面最右的一个不同的数位
2. 第二个pass:对于数组里面的所有的数,和那个最右不同的数位xor,不同的那两个单独的数一定会被分到不同的组,然后对两个组内部再xor一次,就能得到结果:如果结果是0时,也就是说这一位上是设置了的那个,和res[0] xor,否则, 和res[1] xor。
代码:
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int r = 0, n = nums.size(), i = 0, last = 0;
vector<int> ret(2, 0);
for (i = 0; i < n; ++i)
r ^= nums[i];
last = r & (~(r - 1));
for (i = 0; i < n; ++i)
{
if ((last & nums[i]) != 0)
ret[0] ^= nums[i];
else
ret[1] ^= nums[i];
}
return ret;
}
};
- 260.Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- RTMP协议
- 保存微信头像至本地
- Java内存区域和对象布局
- C. Okabe and Boxes
- 01背包问题的扩展——二维费用 LeetCode 474
- 260. Single Number III
- 超全 IntelliJ Idea 快捷键
- Spring Cloud Ribbon(负载均衡)
- 初接触 Sass 与Compass 遇到的几个坑
- 【每天一点Linux】shell脚本的学习之一——符号
- nginx 负载均衡的配置笔记
- FLV学习(三)FlvParser源码阅读(1)总体流程
- 微信小程序周报(第四期)
- github入门到上传本地项目,很详细亲测完美