[Leetcode] Single Number III
来源:互联网 发布:js里的值给input 编辑:程序博客网 时间:2024/06/16 10:19
问题描述:
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?
分析:做了single1,single2再来做这道题发现还是不会,将vector中的元素做异或之后,得到的是两个不同元素的异或值,即两个元素的信息混合在一起。
如何将二者分开,想了好久没想到办法。网友的介绍是利用两个元素的异或值(说明,要找的元素的对应位不同),利用这个特点将原有的序列分为两部分,这样,元素A和元素B分别在两个不同的序列里面了。
转:http://www.lai18.com/content/1577393.html
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?
分析:做了single1,single2再来做这道题发现还是不会,将vector中的元素做异或之后,得到的是两个不同元素的异或值,即两个元素的信息混合在一起。
如何将二者分开,想了好久没想到办法。网友的介绍是利用两个元素的异或值(说明,要找的元素的对应位不同),利用这个特点将原有的序列分为两部分,这样,元素A和元素B分别在两个不同的序列里面了。
这里面还有一个很巧妙的地方是,使用n&(~(n-1))可以取出元素的最后一个1的位置。
代码(C++):
class Solution {public: vector<int> singleNumber(vector<int>& nums) { vector<int> ans(2,0); int aorb=0; for(int i=0;i<nums.size();i++) aorb^=nums[i]; int ma=aorb&(~(aorb-1)); for(int i=0;i<nums.size();i++){ if(ma&nums[i]) ans[0]^=nums[i]; else ans[1]^=nums[i]; } return ans; }};
转:http://www.lai18.com/content/1577393.html
0 0
- [LeetCode] Single Number III
- [leetcode] Single Number III
- [Leetcode]Single Number III
- [leetcode] Single Number III
- Leetcode: Single Number III
- LeetCode || Single Number III
- leetCode---Single Number III
- *LeetCode-Single Number III
- Single Number III -- leetcode
- Leetcode: Single Number III
- [LeetCode] Single Number III
- LeetCode--Single Number III
- leetcode-Single Number III
- LeetCode:Single Number III
- [LeetCode] Single Number III
- LeetCode -- Single Number III
- 【leetcode】Single Number III
- 【Leetcode】Single Number III
- 使用 JMeter 完成常用的压力测试
- mongodb高可用性架构—Replica Set
- String cannot be resolved to a type
- 移植Sqlite2+PHP5.2+apache1.3到ARM平台
- Android gradle 打渠包的一种方式
- [Leetcode] Single Number III
- Cobar使用文档(可用作MySQL大型集群解决方案)
- linux下C/C++程序简单调试
- .Net使用Oracle驱动访问数据库
- ASP.NET企业项目管理系统源码(适用于PM及PMO等)
- LeetCode-100.Same Tree
- RxJava源码走读之map
- 【bzoj3990】【SDOI2015】【排序】【dfs】
- POJ 3254 Corn Fields【状压dp】