Single Number i and ii

Single Number

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

c++版:

class Solution {

public:

   int singleNumber(int arr[] , int length)

{

    int result=arr[0];

    for(int i = 1 ; i < length ; ++i)

        result = result ^ arr[i];

     return result;

 }

};

 Java版:

public class Solution {

    public int singleNumber(int[] A) {

    int result=A[0];

    for(int i=1;i<A.length;i++){

        result=result^A[i];

    }

    return result;

    }

}

  

Single Number II

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

C++版:

class Solution {

public:

  int singleNumber(int A[], int n) {  

    if(n < 0 || n%3 != 1)    return -1;

    map<int, int> mp;

    map<int, int>::iterator it;

    for(int i = 0; i<n; i++) {

        it = mp.find(A[i]);

        if(it == mp.end())

            mp[A[i]] = 1;

        else

           mp[A[i]] += 1;

    }

    for(it = mp.begin(); it != mp.end(); it++) {

        if((*it).second != 3)   return (*it).first;

    }

    }

};

  

你可能感兴趣的:(number)