最近在刷Leetcode时候发现一道这样的题:
136. 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?
题目的要求就是在不利用额外空间的基础上找出数组中没有重复出现的数字,这里用到的是java的异或操作
中心思想就是:java中一个数和自己异或是0的原理
这里给出一个解决方法:
public class SIngleNum {
public int singleNumber(int[] nums) {
int result = 0;
for (int element:nums)
result ^= element;
return result;
}
}
最后给出java中异或(用符号XOR或者 ^ 表示)操作的性质:
1、交换律
2、结合律(即(a^b)^c == a^(b^c))
3、对于任何数x,都有x^x=0,x^0=x
4、自反性 A XOR B XOR B = A xor 0 = A