Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
public class SingleNumber {
/**
* This is classical interview question
* As we know, the same number XOR together will be 0,
* So, XOR all of numbers, the result is the number which only appears once.
* @param a
* @return
*/
static int singleNumber(int[] a) {
int s = 0;
for(int i = 0; i < a.length; i++) {
s = s ^ a[i];
}
return s;
}
public static void main(String[] args) {
int[] a = {1, 1, 2, 3, 2};
System.out.println(singleNumber(a));
}
}
本文介绍了一种线性时间复杂度的算法来找出数组中只出现一次的整数。该算法利用了XOR运算的特性,通过将数组中的所有元素进行XOR操作来实现目标。这种方法巧妙地避免了使用额外内存。
728

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



