개발자식

[Codility lesson2] OddOccurrencesInArray 본문

Algorithm/Codility

[Codility lesson2] OddOccurrencesInArray

밍츠 2022. 6. 23. 23:48

2. OddOccurrencesInArray

 

Test results - Codility

A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. For example, in arr

app.codility.com

 

 나의 풀이

- for문으로 배열을 순회하면서 count() 함수로 개수가 1개이면 바로 return 아니라면 값을 리스트에 넣는다

- 위의 for문을 리스트에 없는 값만 순회

->55% 정답 시간 초과, 시간 복잡도 : O(N2)

 

풀이

from collections import Counter
def solution(A):
    # write your code in Python 3.6

  counted = Counter(A)
  for key, val in counted.items():
    if val %2 !=0 :
      return key

- collectios 모듈의 Counter 클래스 사용

- A에 값이 한개라도 Counter() 가능

- 시간복잡도 O(N) or O(N*log(N))

 

참고

 

+ numpy where 함수 사용하려 하니까 numpy 모듈 없다는 에러 발생, 찾아보니까 라이브러리 제공 다 해준다곤 하는데,, numpy는 안되는 것 같다.

Comments