Single Number

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?

Answer:

int singleNumber(int A[], int n) 
{
    if(n<=0) return -1;
    if(n==1) return A[0];
    sort(A, A + n);  
    int j = 1;
    for(int i = 0; i < n - 1; i++)  
    {
        if(A[i] == A[i+1])
        {
            j++;
        }
        else   
        {
            if(j<2) return A[i];
            j = 1;  
        }
    } 
    return A[n-1];
}
原文地址:https://www.cnblogs.com/ich1990/p/3673667.html