260. Single Number III
来源:互联网 发布:网络翻墙违法吗 编辑:程序博客网 时间:2024/04/25 16:55
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.先异或,得到的值是两个只出现一次的整数的异或值。
2.找出该异或值中第一个不为0的位置,即两个整数不相等的位。
3.根据该位将整数划分为两部分,两个整数分别位于两个部分。异或即可分别得到两个整数。
class Solution {public:vector<int> singleNumber(vector<int>& nums) {int xres = nums[0];for (int i = 1; i < nums.size(); i++){xres ^= nums[i];}int iOne = 0;for (int i = 0; i < 32; i++){if ((xres >> i) & 1){iOne = i;break;}}int res1 = 0, res2 = 0;for (int i = 0; i < nums.size(); i++){if ((nums[i] >> iOne) & 1){res1 ^= nums[i];}else{res2 ^= nums[i];}}vector<int> res;res.push_back(res1);res.push_back(res2);return res;}};
0 0
- 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
- 阶乘
- Qt 学习之路 2笔记3
- FFmpeg源代码简单分析:常见结构体的初始化和销毁(AVFormatContext,AVFrame等)
- 日期控件jeDate和bootstrap datepicker
- Android Studio无法关联Api23源码-提示Souces for android api 23 platform not found
- 260. Single Number III
- 设计模式-装饰模式(理解)
- 关于druid数据连接池抛出的 connection holder is null 异常
- Swift - 滚动选择器
- 可变参数宏__VA_ARGS__
- java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Sessio
- Redis常用几种数据类型
- 安装 Kali Linux 后需要做的 20 件事
- Intent和IntentFilter