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

http://oj.leetcode.com/problems/single-number/


Solution:
Bit operation, use XOR. We know that A^A = 0, A^0 = A. Use a for loop to XOR every element in the array and get the single one.

https://github.com/starcroce/leetcode/blob/master/single_number.cpp

// 52 ms for 14 test cases
class Solution {
public:
    int singleNumber(int A[], int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int ans = 0;
        for(int i = 0; i < n; i++) {
            ans ^= A[i];  // ^ = XOR, a^a = 0, a^a^b = b
        }
        return ans;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章