260. Single Number III #115
-
Topics: Given an integer array 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. You can return the answer in any order. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use bit manipulation, specifically the XOR operation. The key idea is that XORing two identical numbers results in 0, and XORing a number with 0 gives the number itself. Using this property, we can find the two unique numbers that appear only once in the array. Step-by-Step Solution:
Let's implement this solution in PHP: 260. Single Number III <?php
function singleNumber($nums) {
// Step 1: XOR all elements
$xor = 0;
foreach ($nums as $num) {
$xor ^= $num;
}
// Step 2: Find a set bit (rightmost set bit in this case)
$rightmost_set_bit = $xor & (-$xor);
// Step 3: Partition the array into two groups and XOR them
$num1 = 0;
$num2 = 0;
foreach ($nums as $num) {
if (($num & $rightmost_set_bit) == 0) {
$num1 ^= $num;
} else {
$num2 ^= $num;
}
}
return [$num1, $num2];
}
// Example usage:
$nums1 = [1, 2, 1, 3, 2, 5];
$result1 = singleNumber($nums1);
print_r($result1);
$nums2 = [-1, 0];
$result2 = singleNumber($nums2);
print_r($result2);
$nums3 = [0, 1];
$result3 = singleNumber($nums3);
print_r($result3);
?> Explanation:
This solution runs in O(n) time and uses O(1) extra space, meeting the problem's requirements. |
Beta Was this translation helpful? Give feedback.
We can use bit manipulation, specifically the XOR operation. The key idea is that XORing two identical numbers results in 0, and XORing a number with 0 gives the number itself. Using this property, we can find the two unique numbers that appear only once in the array.
Step-by-Step Solution:
XOR all elements in the array. The result will be the XOR of the two unique numbers because all other numbers will cancel out (since they appear twice).
Find a set bit in the XOR result (this bit will be different between the two unique numbers). You can isolate the rightmost set bit using
xor & (-xor)
.Partition the array into two groups based on the set bit. XOR all numbers in each group to fin…