#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
所有,並有從0 hash
陣列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
和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;
}
問題是什麼? – 2011-03-13 20:53:52
如何刪除O(n)運行時間中的重複項? – Ava 2011-03-13 20:54:37
也許你應該把這個問題本身... – 2011-03-13 20:55:16