#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
을 음의 배열 인덱스를 가지고 200
std::vector
와
#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::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;
}
0에서
hash
배열을 질수
무엇이 문제입니까? –
O (n) 실행 시간에 복제본을 제거하려면 어떻게해야합니까? – Ava
어쩌면 당신은 그 질문 자체에 넣어야합니다 ... –