[LeetCode] Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Could you implement it without using extra memory?


Solution: 利用異或的可交換性!!!!!!!!!!!!!!

class Solution {
public:
    int singleNumber(int A[], int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(n==0)
            return 0;
        
        int result=A[0];
        for(int i=1;i<n;i++)
        {
            result^=A[i];
        }
        return result;
    }
};


發佈了110 篇原創文章 · 獲贊 4 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章