leetcode260-single number iii
題目:
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 class Solution {
public int[] singleNumber(int[] nums) {
if (nums==null || nums.length==0)
return new int[]{};
if(nums.length==1)
return new int[]{ nums[0] };
// get the xor result of the two single numbers
int xor = 0;
for (int num : nums)
xor ^= num;
// divide the numbers into two groups, get the mask to calculate which group will each number be put in
int mask = 0;
if (xor==0) {
return new int[]{};
} else if (xor>0) {
for (int i=1; i<32; i++) {
int remainder = xor%2;
if (remainder>0) {
mask = 1 << (i-1);
break;
}
xor = xor/2;
}
} else {
mask = Integer.MIN_VALUE;
}
// num1 is the xor result for group 1, and num2 is for group2
int num1 = 0;
int num2 = 0;
for (int num : nums) {
int group = num & mask;
if (group==0)
num1 ^= num;
else
num2 ^= num;
}
return new int[]{num1, num2};
}
}
相關文章
- LintCode-Majority Number III
- [LeetCode] 248. Strobogrammatic Number IIILeetCode
- Leetcode 之 PHP 解析 (260. Single Number III)LeetCodePHP
- Hackable: III
- A - 卡牌遊戲 III遊戲
- Chapter III What Is Truth IIAPT
- 劍指 Offer 32 - III. 從上到下列印二叉樹 III二叉樹
- 「譯」MotionLayout介紹 (part III)
- Delphi物件模型(Part III) (轉)物件模型
- JavaScript Number()JavaScript
- Oracle System Change Number (SCN) Number 完全筆記Oracle筆記
- 【iCore3 雙核心板_ uC/OS-III】例程一:認識 uC/OS-III
- 如何移植uCOS-III到Linux系統 How to Port uCOS-III on Linux OSLinux
- SAP HUM 巢狀HU初探 III巢狀
- LeetCode-House Robber IIILeetCode
- LintCode-Maximum Subarray III
- boost::iterator_adaptor (III) (轉)APT
- 【NUMBER】Oracle的NUMBER資料型別特點Oracle資料型別
- JavaScript Number 物件JavaScript物件
- Number.NaNNaN
- Number of BoomerangsOOM
- react input[type='number']React
- JavaScript Number toLocaleString()JavaScript
- JavaScript Number toString()JavaScript
- Number.POSITIVE_INFINITY
- Number.ATIVE_INFINITY
- Number.isNaN()方法NaN
- Number.isFinite()方法
- Js中的NumberJS
- Where is the SCN number written?
- LeetCode-Shortest Word Distance IIILeetCode
- 【LeetCode】House Robber III(337)LeetCode
- oracle administrator's guide Part IIIOracleGUIIDE
- Best Time to Buy and Sell Stock III -- LeetCodeLeetCode
- On Designing Good Libraries -- Part III (轉)Go
- 7.34 BITMAP_BUCKET_NUMBER
- 7.104 ITERATION_NUMBER
- Leetcode Number of islandsLeetCode