260. Single Number III
来源:互联网 发布:软件测试举例 编辑:程序博客网 时间:2024/04/20 03:14
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?
public int[] singleNumber(int[] nums){int len=nums.length;if(len<1)return new int[]{};HashSet<Integer> hashset=new HashSet<>(len);for(int a:nums)if(!hashset.contains(a))hashset.add(a);else {hashset.remove(a);}int[] retarr=new int[hashset.size()];Iterator<Integer> it=hashset.iterator();int cnt=0;while(it.hasNext())retarr[cnt++]=it.next();return retarr;}
Once again, we need to use XOR to solve this problem. But this time, we need to do it in two passes:
In the first pass, we XOR all elements in the array, and get the XOR of the two numbers we need to find. Note that since the two numbers are distinct, so there must be a set bit (that is, the bit with value '1') in the XOR result. Find out an arbitrary set bit (for example, the rightmost set bit).
In the second pass, we divide all numbers into two groups, one with the aforementioned bit set, another with the aforementinoed bit unset. Two different numbers we need to find must fall into thte two distrinct groups. XOR numbers in each group, we can find a number in either group.
public int[] singleNumber(int[] nums) { // Pass 1 : // Get the XOR of the two numbers we need to find int diff = 0; for (int num : nums) { diff ^= num; } // Get its last set bit diff &= -diff; // Pass 2 : int[] rets = {0, 0}; // this array stores the two numbers we will return for (int num : nums) { if ((num & diff) == 0) // the bit is not set { rets[0] ^= num; } else // the bit is set { rets[1] ^= num; } } return rets; }
- 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
- UVa11235 sparse-table RLE
- 自定义漂亮的seekBar,内带popwindow及指示器
- pull解析
- Spring动态多数据源实例Demo
- [bfs 分层图 字典序 最短路] BZOJ 2644 Pku3967 Ideal Path
- 260. Single Number III
- 166. Fraction to Recurring Decimal
- 24. Swap Nodes in Pairs
- Android ListView 图片异步加载和图片内存缓存
- eclipse安装反编译插件步骤
- java 数组的初始化
- eclipse4.4.2使用maven
- 一些程序段分析(1)
- gradleb编译的finished with non-zero exit value问题