题目
Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
题解
运用异或运算,异或xor满足一个特殊的性质,即a xor a == 0,因此,将整个输入数组异或起来的话,出现偶数次的数将会全部被抵消掉,仅剩下唯一的,出现了奇数次的数。
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.*; import java.io.*; class FindOdd { public static int findIt(int[] a) { int result = 0; for (int w:a) { result ^= w; } return result; } } |
当然,这个实现方式最简单的代码应该是——
1 2 3 4 5 6 7 |
import static java.util.Arrays.stream; public class FindOdd { public static int findIt(int[] arr) { return stream(arr).reduce(0, (x, y) -> x ^ y); } } |
和之前TwoToOne那一道题相似,运用到了stream类,不同的是,这次使用了stream类的reduce函数。