[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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章