code第一部分數組:第二十二題 偶數次中查找單獨出現一次的數

code第一部分數組:第二十二題 偶數次中查找單獨出現一次的數

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

分析:採用異或的方法查找;數組

 

#include <iostream>
using namespace std;

int singleNumber(int A[], int n)
{
    int x = A[0];
    for (int i = 1; i < n; ++i)
    {
        x ^= A[i];
    }

    return x;
}


int main()
{
    int a[7]={1,3,4,4,3,2,1};
    int ans=singleNumber(a,7);

    cout<<"the ans is "<<ans;
    return 0;
}
這種方法不只能解決兩次中單獨一次的狀況,偶數次中單獨出現一次的狀況也能找出來。
 
若是能使用額外空間,也可使用hash表來作。
相關文章
相關標籤/搜索