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?
题目意思是一个数组中,只有一个元素是唯一的,其他元素都是两次出现的。要求算法时间复杂度为o(n),并且不开辟额外内存
方法是使用异或运算。
0 ^ x = x x ^ x = 0
首先设val = 0,最后返回 val 。 其中 val = val ^ a1 ^ a2 ... ^ an。 由于其中两两相同的在异或中已经为0了,所以最后结果就是那个唯一的数。
Source
public class Solution {
public int singleNumber(int[] A) {
int val = 0;
for(int i = 0; i < A.length; i++){
val = val ^ A[i];
}
return val;
}
}
Test
public static void main(String[] args){
int[] numbers = {7, 2, 3, 4, 7, 3, 4};
int b = new Solution().singleNumber(numbers);
System.out.println(b);
}