传送门

Description

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?

思路

题意:给定一个数组,其中除了两个数出现一次外,其他都出现两次,要求在时间复杂度为O(n)空间复杂度为O(1)的条件下找出这两个数。

题解:按照异或的思想,最后可以得到这两个出现一次的数的异或值,那么我们只需对这个异或值lowbit操作,得到其最低位为1的位在哪,然后根据lowbit后得到的值,将数据分为两堆,那么可以知道的是这两个出现一次的数肯定分布在不同的两堆中(因为是对这这两个数的异或值lowbit操作,因此其为1的最低二进制位,这两个数肯定一个数0一个是1),那么问题转化为子问题,有一堆数,出了一个数出现一次外,其他数都出现两次。

class Solution {
public:
//26ms
vector<int> singleNumber(vector<int>& nums) {
int diff = 0,one = 0,two = 0;
vector<int>res;
for (unsigned int i = 0;i < nums.size();i++){
diff ^= nums[i];
}
diff &= (-diff); //lowbit操作
for (unsigned int i = 0;i < nums.size();i++){
if (nums[i] & diff) one ^= nums[i];
else two ^= nums[i];
}
res.push_back(one);
res.push_back(two);
return res;
}
};

  

 

最新文章

  1. Esfog_UnityShader教程_溶解效果Dissolve
  2. Mac: Jdk版本切换
  3. Linux内核循环链表经典分析和移植
  4. 解决Ue4C++使用UMG之类的模块时出现的拼写错误
  5. svn status 显示 ~xx
  6. MAC中开发Unity3D
  7. #import vs. @class
  8. 用JS写的放大镜
  9. AndroidPN中的心跳检测
  10. F - Wormholes
  11. asp.net [AjaxMethod]
  12. PHPEXCEL实例-导出EXCEL
  13. Spring Cloud 学习笔记(二)——Netflix
  14. 在linux ubuntu下搭建深度学习/机器学习开发环境
  15. 使用 pandas 导出数据
  16. Python&#160;一键上传下载&amp;一键提交文件到SVN入基线工具
  17. WinRAR从入门到高级的操作技巧集合
  18. Mybatis 逆向工程学习随笔
  19. dhroid - eventbus 事件总线
  20. mac securecrt无法记住密码的解决方法

热门文章

  1. django实例收集
  2. SSM商城系统开发笔记-问题01-通配符的匹配很全面, 但无法找到元素 &#39;mvc:annotation-driven&#39; 的声明。
  3. RabbitMQ相关使用命令
  4. git 和码云的上传文件代码操作
  5. 2019-4-21-Roslyn-通过-NuGet-库修改应用程序入口函数
  6. 阿里P7前端需要哪些技能
  7. wangeditor 支持上传视频版
  8. 前端每日实战:43# 视频演示如何用纯 CSS 绘制一个充满动感的 Vue logo
  9. windows cmd bat处理文件
  10. sed 搜索并替换