例子比如{1,1,2,2,3}找出3。
本题目考察的异或运算。
1、相同的数异或为0。 1^1=0
2、其他数与0异或为本身。0^1=0
1^1^2^2^3=3
public static int singleNumber(int[] A) {
int result = A[0];
for(int i=1; i<A.length; i++){
result = result ^ A[i];
}
return result;
}
本文介绍了一种使用异或运算找出数组中唯一元素的方法。通过异或运算的特性,相同元素相互抵消,最终得到唯一出现的元素。文章提供了一个具体的Java代码示例,演示了如何实现这一算法。
例子比如{1,1,2,2,3}找出3。
本题目考察的异或运算。
1、相同的数异或为0。 1^1=0
2、其他数与0异或为本身。0^1=0
1^1^2^2^3=3
public static int singleNumber(int[] A) {
int result = A[0];
for(int i=1; i<A.length; i++){
result = result ^ A[i];
}
return result;
}
2022
432
343

被折叠的 条评论
为什么被折叠?