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?app

數組中除了某個元素出現一次,其餘都出現兩次,找出只出現一次的元素。spa

一個數字和本身異或 結果爲 0,一個數字與0異或 結果還爲它本身code

好比數組:[6,6,3]  ,6和6異或爲0,0與3異或爲3,所以將數組中全部的元素異或一遍即爲最終的結果:blog

 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 }
相關文章
相關標籤/搜索