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^2),不符合要求。之后在讨论区看到了优秀的算法。利用异或的特性A^B^A=B。
- public int singleNumber(int[]A){
- int result = 0;
- for (int i = 0; i<A.length; i++)
- {
- result ^=A[i];
- }
- return result;
- }