LeetCode136:Single Number

mickole發表於2014-02-18

題目:

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與任何數異或結果為原數

也可先進行排序再遍歷排序後的陣列,當某個數沒有重複時,結果就是它了

也可用bitmap進行,不多說了。

實現程式碼:

#include <iostream>

using namespace std;
/*
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?
*/
class Solution {
public:
    int singleNumber(int A[], int n) {
        int ret = 0;
        for(int i = 0; i < n; i++)
            ret ^= A[i];
        return ret;
        
    }
};

int main(void)
{
    int arr[] = {2,4,5,5,4,1,2};
    int len = sizeof(arr) / sizeof(arr[0]);
    Solution solution;
    int once = solution.singleNumber(arr, len);
    cout<<once<<endl;
    return 0;
}

相關文章