/**
* Source : https://oj.leetcode.com/problems/single-number/
*
*
* 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 {
/**
* 数组中每个元素都有相同的两个,只有其中一个元素是只有一个的,找出这个元素
* 1. 对数组排序,将arr[i] 和arr[i-1]、arr[i+1]进行比较,如果又都不相等,那么就是要找的元素
* 2. 使用hash表,循环数组,判断hash表中是否有这个元素,如果有则删除hash表的元素,否则将当前元素加入hash表,最后hash表中剩下的是要找的元素
* 3. 使用异或运算,xor,一个数和自身异或运算为0,x^x = 0, x^0 = x
*
* @param arr
* @return
*/
public int singleNumber (int[] arr) {
int res = 0;
for (int i = 0; i < arr.length; i++) {
res ^= arr[i];
}
return res;
}
public static void main(String[] args) {
SingleNumber singleNumber = new SingleNumber();
System.out.println(singleNumber.singleNumber(new int[]{1,1,2,2,3}) + " == 3");
}
}