260. Single Number III
来源:互联网 发布:比较好的淘宝培训机构 编辑:程序博客网 时间:2024/03/28 23:44
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?
这个应该是剑指offer的一道题,具体思路如下:
先对所有数字异或一遍,再用mask=t&(~(t-1));求出最右边的一个1的位置。
再以那个位置是否为1,将所有的数字划分为2组,a和b一定分别在其中的一组。
这个时候就可以直接异或分别得到那两个数字了。
class Solution {public: vector<int> singleNumber(vector<int>& nums) { int t=0; for(int i=0;i<nums.size();i++){ t^=nums[i]; } int mask=t&(~(t-1)); int a=0,b=0; for(int i=0;i<nums.size();i++){ if(mask&nums[i]) a^=nums[i]; else b^=nums[i]; } return vector<int>({a,b}); }};
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
- SQL索引一步到位(
- Windows之Xmanager连接linux打开Oracle视图操作
- squid源码分析4—coss存储机制分析
- 有趣的数组
- lightoj 1110 - An Easy LCS 最长公共子序列输出路径
- 260. Single Number III
- spring4整合hibernate5.1
- jquery插件资源
- A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS
- 前端开发我为什么选择cordova
- 1012 - Guilty Prince(无脑bfs)
- 钻石型虚拟多重继承的C++对象内存模型
- 关于Git和Github你不知道的十件事
- 宜信笔试题--编程题