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};
}
}
相關文章
- 260-Single Number III
- [LeetCode] 248. Strobogrammatic Number IIILeetCode
- Leetcode 之 PHP 解析 (260. Single Number III)LeetCodePHP
- Hackable: III
- Reflective Journal III
- Path Sum III
- Diablo III ZOJ - 3769
- P110 III
- JavaScript Number()JavaScript
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- 337-House Robber III
- 437-Path Sum III
- A - 卡牌遊戲 III遊戲
- 劍指 Offer 32 - III. 從上到下列印二叉樹 III二叉樹
- 「譯」MotionLayout介紹 (part III)
- [LeetCode] 3163. String Compression IIILeetCode
- vulnhub靶場之HACKABLE: III
- Kata:Hamming number
- JavaScript Number toLocaleString()JavaScript
- JavaScript Number toString()JavaScript
- Number.NaNNaN
- JavaScript Number 物件JavaScript物件
- Leetcode Number of islandsLeetCode
- 力扣 170. 兩數之和 III - 資料結構設計 two-sum III力扣資料結構
- 理光gr3 GR III 替代
- SAP HUM 巢狀HU初探 III巢狀
- 437. 路徑總和 III
- Perfect Number 完美數
- [LeetCode] Third Maximum NumberLeetCode
- [LeetCode] Find the Duplicate NumberLeetCode
- Leetcode 9 Palindrome NumberLeetCode
- Number.parseInt() 方法
- Number.parseFloat()方法
- Number.isSafeInteger()方法
- Number.isNaN()方法NaN
- Number.isFinite()方法
- Js中的NumberJS
- Number.POSITIVE_INFINITY
- Number.ATIVE_INFINITY