260. Single Number III
O texto da tarefa é traduzido do russo para o idioma selecionado. O código permanece sem alterações.
Дан inteiro array nums, в котором ровно два elementа встречаются только один раз, а все остальные elementы встречаются ровно дважды. find два elementа, которые встречаются только один раз. Вы можете вернуть ответ в любом порядке.
C# solução
correspondente/originalpublic class Solution {
public int[] SingleNumber(int[] nums) {
int xor = 0;
foreach (int num in nums) {
xor ^= num;
}
int diff = xor & -xor;
int[] res = new int[2];
foreach (int num in nums) {
if ((num & diff) == 0) {
res[0] ^= num;
} else {
res[1] ^= num;
}
}
return res;
}
}
C++ solução
rascunho automático, revisar antes de enviar#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public vector<int>& SingleNumber(vector<int>& nums) {
int xor = 0;
foreach (int num in nums) {
xor ^= num;
}
int diff = xor & -xor;
vector<int>& res = new int[2];
foreach (int num in nums) {
if ((num & diff) == 0) {
res[0] ^= num;
} else {
res[1] ^= num;
}
}
return res;
}
}
Java solução
correspondente/originalclass Solution {
public int[] singleNumber(int[] nums) {
int xor = 0;
for (int num : nums) {
xor ^= num;
}
int diff = xor & -xor;
int[] res = new int[2];
for (int num : nums) {
if ((num & diff) == 0) {
res[0] ^= num;
} else {
res[1] ^= num;
}
}
return res;
}
}
JavaScript solução
correspondente/originalclass Solution {
singleNumber(nums) {
let xor = 0
for (const num of nums) {
xor ^= num
}
const diff = xor & -xor
const res = [0, 0]
for (const num of nums) {
if ((num & diff) === 0) {
res[0] ^= num
} else {
res[1] ^= num
}
}
return res
}
}
Python solução
correspondente/originalclass Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
xor = 0
for num in nums:
xor ^= num
diff = xor & -xor
res = [0, 0]
for num in nums:
if num & diff == 0:
res[0] ^= num
else:
res[1] ^= num
return res
Go solução
correspondente/originalfunc singleNumber(nums []int) []int {
xor := 0
for _, num := range nums {
xor ^= num
}
diff := xor & -xor
res := []int{0, 0}
for _, num := range nums {
if num&diff == 0 {
res[0] ^= num
} else {
res[1] ^= num
}
}
return res
}
Algorithm
Exemplo:
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
👨💻
Algoritmo:
1️⃣
Выполните XOR для всех elementов arrayа nums. Это даст результат, который является XOR двух уникальных чисел.
2️⃣
find бит, который отличается в этих двух числах, чтобы разделить все числа в arrayе на две группы.
3️⃣
Выполните XOR для каждой группы, чтобы find два уникальных числа.
😎
Vacancies for this task
vagas ativas with overlapping task tags are mostradas.
Ainda não há vagas ativas.