260-Single Number III
Description
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?
問題描述
給定整數陣列nums, 除了兩個數只出現一次, 其他數都出現了兩次, 找出這兩個只出現了一次的數
問題分析
兩次迴圈處理
- 第一次。 異或所有元素, 得到res1 和 res2的異或(由於相等的元素異或為0, 所以消去了)
- 第二次。由於res1和res2不同, 那麼我們得到最右邊的不同的那一位,通過這一位將nums分為兩組(使用&為0一組, 使用&不為0一組),分別對兩組數異或, 得到結果(注意, 相等的元素一定落到同一組, 因此消去)
解法
public class Solution {
public int[] singleNumber(int[] nums) {
if(nums == null || nums.length <= 1) return new int[2];
int diff = nums[0];
//第一次迴圈, 求出res1和res2的異或
for(int i = 1; i<nums.length; i++) diff ^= nums[i];
//算出最右邊的不同的那一位
diff &= -diff;
int res1 = 0, res2 = 0;
//將元素分為兩組, 分別異或
for(int num:nums){
if((num & diff) == 0) res1 ^= num;
else res2 ^= num;
}
return new int[]{res1, res2};
}
}
相關文章
- [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
- A - 卡牌遊戲 III遊戲
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- 337-House Robber III
- 437-Path Sum III
- 劍指 Offer 32 - III. 從上到下列印二叉樹 III二叉樹
- JavaScript Number 物件JavaScript物件
- Leetcode Number of islandsLeetCode
- Kata:Hamming number
- JavaScript Number toLocaleString()JavaScript
- JavaScript Number toString()JavaScript
- Number.NaNNaN
- [LeetCode] 3163. String Compression IIILeetCode
- vulnhub靶場之HACKABLE: III
- 「譯」MotionLayout介紹 (part III)
- 力扣 170. 兩數之和 III - 資料結構設計 two-sum III力扣資料結構
- 理光gr3 GR III 替代
- 437. 路徑總和 III
- SAP HUM 巢狀HU初探 III巢狀
- Serial number lookup for Panasonic
- D. The Number of Imposters
- Big Number hd 1212
- 7.104 ITERATION_NUMBER
- Leetcode 447 Number of BoomerangsLeetCodeOOM
- react input[type='number']React
- number(p,s)(轉)
- Last digit of a huge numberASTGit
- [HNU 10072] Fibonacci Number
- Python Number(數字)Python
- Perfect Number 完美數
- [LeetCode] Third Maximum NumberLeetCode