본문 바로가기
📖 Coding Test/Codility

[Swift] Codility Lesson 2 - OddOccurrencesInArray

by hyebin (Helia) 2022. 7. 23.

문제

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 array A such that:

A[0] = 9, A[1] = 3, A[2] = 9, A[3] = 3, A[4] = 9, A[5] = 7, A[6] = 9

the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.

Write a function:

public func solution(_ A : inout [Int]) -> Int

that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.

For example, given array A such that:

A[0] = 9, A[1] = 3, A[2] = 9, A[3] = 3, A[4] = 9, A[5] = 7, A[6] = 9

the function should return 7, as explained in the example above.

Write an efficient algorithm for the following assumptions:

N is an odd integer within the range [1..1,000,000];

each element of array A is an integer within the range [1..1,000,000,000];

all but one of the values in A occur an even number of times.

 

링크

 

OddOccurrencesInArray coding task - Learn to Code - Codility

Find value that occurs in odd number of elements.

app.codility.com

 

문제 분석

  • N개의 정수로 구성된 배열 A가 입력으로 주어진다. (N은 홀수)
  • 배열 A에서 한 요소를 제외한 나머지 요소들끼리는 동일한 값을 갖는 요소끼리 쌍을 이룰 수 있다.
  • 쌍을 이루지 않는 요소의 값을 반환한다.
ex) A = [4, 6, 8, 9, 9, 6, 4]

A[0] == A[6] => 4
A[1] == A[5] => 6
A[3] == A[4] => 9

=> A[2] = 8

 

해결방안 1 - 실패

  1. 배열 A의 개수가 0이라면 0번째 요소를 반환
  2. 배열 A의 첫 번째 요소를 변수에 저장한 후 삭제
  3. 배열 A에 변수 값과 같은 값을 가진 요소가 있는지 확인
    1. 같은 값을 가진 요소가 있다면 해당 요소를 배열에서 삭제
    2. 같은 값을 가진 요소가 없다면 반복문을 멈추고 변수의 값을 반환
  4. 2,3번 과정을 반복

 

Solution 1

public func solution(_ A : inout [Int]) -> Int {
    if A.count == 1{
        return A[0]
    }
    var temp = 0

    while true{
        temp = A.removeFirst()
        if A.contains(temp){
            A.remove(at: A.firstIndex(of: temp)!)
        }else{
            break
        }
    }
    return temp
}

 

  • 입력이 큰 경우 timeout 오류 발생
  • 시간 복잡도: O(N**2)

 

해결방안 2

  1. 배열 A의 요소를 순서대로 temp 변수와 XOR 연산한다.
    • XOR 연산은 2진수 두 개를 연산하여 각 자리의 값이 같으면 0, 다르면 1을 반환
    • 값이 같은 경우에는 XOR 연산에서 0으로 무시되기 때문에 짝을 이루지 않는 원소만 남음

Solution 2

public func solution(_ A : inout [Int]) -> Int {
    var temp = 0
    
    for item in A {
        temp ^= item
    }
    
    return temp
}

  • 시간 복잡도: O(N) or O(N*log(N))
반응형

댓글