#include <iostream>
void find_odd(int a[])
{
int hash[101] = { 0 };
int i;
for( i = 0 ; i < 6 ; i++ )
{
hash[ a[i] ]++;
}
for(i=0 ; i<100 ; i++)
if(hash[i] != 0 && !(hash[i] % 2 == 0))
std::cout << i << std::endl;
}
int main()
{
int a[] = {1,3,3,5,5,5};
find_odd(a);
return 0;
}
但是您可能会更好地使用std::vector
和/或std::map
.
带负数:但仅在 -100 -> +100 范围内。你不能有一个负数组索引,所以+100
对所有人来说,hash
数组从 0 到 200。
#include <iostream>
void find_odd(int a[])
{
int hash[201] = { 0 };
int i;
for( i = 0 ; i < 9 ; i++ )
{
hash[ a[i]+100 ]++;
}
for(i=0 ; i<201 ; i++)
if(hash[i] != 0 && !(hash[i] % 2 == 0))
std::cout << i-100 << std::endl;
}
int main()
{
int a[] = {-1 , -1 , -1 , 1 , 3 , 3 , 5 , 5 , 5};
find_odd(a);
return 0;
}
使用std::vector
and std::map
(适用于正数和负数)
#include <iostream>
#include <map>
#include <vector>
void find_odd_mapped(std::vector<int>& a)
{
std::map<int , int> hash;
std::map<int , int>::iterator map_iter;
std::vector<int>::iterator vec_iter;
for( vec_iter = a.begin() ; vec_iter != a.end() ; ++vec_iter )
++hash[*vec_iter];
for(map_iter = hash.begin() ; map_iter != hash.end() ; ++map_iter)
if(!((*map_iter).second % 2 == 0))
std::cout << (*map_iter).first << std::endl;
}
int main()
{
std::vector<int> a;
a.push_back(-1);
a.push_back(-1);
a.push_back(-1);
a.push_back(1);
a.push_back(3);
a.push_back(3);
a.push_back(5);
a.push_back(5);
a.push_back(5);
find_odd_mapped(a);
return 0;
}