반응형
Description:
Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
Examples
[7] should return 7, because it occurs 1 time (which is odd).
[0] should return 0, because it occurs 1 time (which is odd).
[1,1,2] should return 2, because it occurs 1 time (which is odd).
[0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
[1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).
Solution:
1. Count the number of identical elements.
2. If the number of elements is odd, the element is returned.
def find_it(seq):
for i in set(seq):
if seq.count(i)&1:
return i
How to solve using the collections built-in function.
import collections
def find_it(seq):
for k, v in collections.Counter(seq).items():
if v&1:
return k
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
Jaden Casing Strings (0) | 2022.04.01 |
---|---|
Complementary DNA (0) | 2022.03.31 |
Sum of the first nth term of Series (0) | 2022.03.29 |
Reverse words (0) | 2022.03.28 |
Invert values (0) | 2022.03.27 |