260. Single Number III
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.
Дан 정수 배열 nums, в котором ровно два elementа встречаются только один раз, а все остальные elementы встречаются ровно дважды. find два elementа, которые встречаются только один раз. Вы можете вернуть ответ в любом порядке.
C# 해법
매칭됨/원본public 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++ 해법
자동 초안, 제출 전 검토#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 해법
매칭됨/원본class 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 해법
매칭됨/원본class 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 해법
매칭됨/원본class 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 해법
매칭됨/원본func 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
예제:
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
👨💻
알고리즘:
1️⃣
Выполните XOR для всех elementов 배열а nums. Это даст результат, который является XOR двух уникальных чисел.
2️⃣
find бит, который отличается в этих двух числах, чтобы разделить все числа в 배열е на две группы.
3️⃣
Выполните XOR для каждой группы, чтобы find два уникальных числа.
😎
Vacancies for this task
활성 채용 with overlapping task tags are 표시됨.
아직 활성 채용이 없습니다.