260. Single Number III

Given an array of numbersnums, 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:
Givennums = [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的数,也就是第一个不一样位值的数字, 比如001^101 == 100, 最后一位不相等的数字就是第一位的1. 怎么求出 A &~(A-1) =100

然后用这个数再逐个与上数组中的每个值, 根据与的值1 / 0 剥离开。


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容