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?
陣列中除了某個元素出現一次,其他都出現兩次,找出只出現一次的元素。
一個數字和自己異或 結果為 0,一個數字與0異或 結果還為它自己
比如陣列:[6,6,3] ,6和6異或為0,0與3異或為3,因此將陣列中所有的元素異或一遍即為最終的結果:
1 public class Solution { 2 public int singleNumber(int[] A) { 3 4 int n = A.length; 5 int result = 0; 6 7 for(int i = 0 ; i < n ; i ++) 8 result ^= A[i]; 9 10 return result; 11 } 12 }