1. 程式人生 > >LeetCode刷題之一:尋找只出現一次的數字

LeetCode刷題之一:尋找只出現一次的數字

題目為:

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?

解題思路為:其他數字都出現兩次,只有一個數字出現一次,思考要用什麼方法才能讓那些出現兩次的數字經過某個操作能相互消除呢?那就是異或操作

程式碼為:
public class Solution {
    public int singleNumber(int[] A) {
        int result = 0;
        for(int number: A)
            result = result ^ number;
        return result;
    }
}