跳转至

3158. 求出出现两次数字的 XOR 值

题目描述

给你一个数组 nums ,数组中的数字 要么 出现一次,要么 出现两次。

请你返回数组中所有出现两次数字的按位 XOR 值,如果没有数字出现过两次,返回 0 。

 

示例 1:

输入:nums = [1,2,1,3]

输出:1

解释:

nums 中唯一出现过两次的数字是 1 。

示例 2:

输入:nums = [1,2,3]

输出:0

解释:

nums 中没有数字出现两次。

示例 3:

输入:nums = [1,2,2,1]

输出:3

解释:

数字 1 和 2 出现过两次。1 XOR 2 == 3 。

 

提示:

  • 1 <= nums.length <= 50
  • 1 <= nums[i] <= 50
  • nums 中每个数字要么出现过一次,要么出现过两次。

解法

方法一:计数

我们定义一个数组或哈希表 $\textit{cnt}$ 记录每个数字出现的次数。

接下来,遍历数组 $\textit{nums}$,当某个数字出现两次时,我们将其与答案进行异或运算。

最后返回答案即可。

时间复杂度 $O(n)$,空间复杂度 $O(M)$。其中 $n$ 是数组 $\textit{nums}$ 的长度,而 $M$ 是数组 $\textit{nums}$ 中的最大值或数组 $\textit{nums}$ 不同数字的个数。

1
2
3
4
class Solution:
    def duplicateNumbersXOR(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        return reduce(xor, [x for x, v in cnt.items() if v == 2], 0)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    public int duplicateNumbersXOR(int[] nums) {
        int[] cnt = new int[51];
        int ans = 0;
        for (int x : nums) {
            if (++cnt[x] == 2) {
                ans ^= x;
            }
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
public:
    int duplicateNumbersXOR(vector<int>& nums) {
        int cnt[51]{};
        int ans = 0;
        for (int x : nums) {
            if (++cnt[x] == 2) {
                ans ^= x;
            }
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func duplicateNumbersXOR(nums []int) (ans int) {
    cnt := [51]int{}
    for _, x := range nums {
        cnt[x]++
        if cnt[x] == 2 {
            ans ^= x
        }
    }
    return
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function duplicateNumbersXOR(nums: number[]): number {
    const cnt: number[] = Array(51).fill(0);
    let ans: number = 0;
    for (const x of nums) {
        if (++cnt[x] === 2) {
            ans ^= x;
        }
    }
    return ans;
}

评论