输入:nums = [2,2,1]
输出:1
public static void main(String[] args) {
int[] nums = {4, 1, 2, 1, 2};
// 方式一:
way1(nums);
// 方式二:
way2(nums);
}
/**
* 方式一:使用 HashSet实现
*
* @param nums
*/
private static void way2(int[] nums) {
// 获取数组只有一个的元素
HashSet<Integer> hashSet = new HashSet<>();
for (int num : nums) {
if (!hashSet.add(num)) {
hashSet.remove(num);
}
}
int next = hashSet.iterator().next();
System.out.println("way1: " + next);
}
原理:
/**
* 方式二:使用 异或实现
*
* @param nums
*/
private static void way1(int[] nums) {
// 使用异或获取结果
int result = 0;
for (int num : nums) {
result ^= num;
}
System.out.println("way2: " + result);
}
原理:
异或运算的规则如下:
简单的异或案例:
public class XORExample {
public static void main(String[] args) {
int num1 = 5; // 二进制:0101
int num2 = 3; // 二进制:0011
// 使用异或运算
int result = num1 ^ num2;
System.out.println("num1 异或 num2 的结果:" + result); // 输出:6
}
}
在这个例子中,我们有两个整数 num1 和 num2,它们的二进制表示分别为 0101 和 0011。通过异或运算,对应位上相同的数会得到0,不同的数得到1。因此,num1 ^ num2 的结果为 0110,对应的十进制值为6。
力扣:https://leetcode.cn/leetbook/read/top-interview-questions/xm0u83/