본문 바로가기
📖 Coding Test/Codility

[Swift] Codility Lesson 5 - PassingCars

by hyebin (Helia) 2022. 7. 26.

문제

A non-empty array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.

Array A contains only 0s and/or 1s:

0 represents a car traveling east,
1 represents a car traveling west.

The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.

For example, consider array A such that:

A[0] = 0 A[1] = 1 A[2] = 0 A[3] = 1 A[4] = 1

We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).

Write a function:

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

that, given a non-empty array A of N integers, returns the number of pairs of passing cars.

The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.

For example, given:

A[0] = 0 A[1] = 1 A[2] = 0 A[3] = 1 A[4] = 1

the function should return 5, as explained above.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..100,000];
each element of array A is an integer that can have one of the following values: 0, 1.

 

문제 링크

https://app.codility.com/programmers/lessons/5-prefix_sums/passing_cars/

 

PassingCars coding task - Learn to Code - Codility

Count the number of passing cars on the road.

app.codility.com

GitHub

https://github.com/yoohyebin/swift/tree/main/Codility

 

GitHub - yoohyebin/swift

Contribute to yoohyebin/swift development by creating an account on GitHub.

github.com

 

문제 분석

  • N개의 정수로 구성된 배열 A가 입력으로 주어진다.
  • 배열 A의 요소는 도로의 자동차를 나타냅니다.
  • 배열 A는 0과 1로만 구성되어 있는데, 0은 동쪽으로 이동하는 차, 1은 서쪽으로 이동하는 차를 나타냅니다.
  • 지나가는 자동차의 쌍의 수를 반환하는 문제이다. (P, Q) < 0 P < Q < N >

해결방안

  1. 동쪽으로 가는 차 (A [i] = 0)가 늘어날 때마다 pCount 값을 증가
  2. 서쪽으로 가는 차가 있을 때마다 pCount 값을 sum에 저장
차량 번호 차량 방향 차량과 passing 하는
순서쌍
차량과 passing 하는
차량 수 
총 passing car
0 0 - 0 0
1 1 (0,1) 1 1
2 0 - 0 1
3 1 (0,3), (2,3) 2 3
4 1 (0,4), (2,4) 2 5

Solution

public func solution(_ A : inout [Int]) -> Int {
    var pCount = 0, sum = 0

    for a in A{
        if a == 0 {pCount += 1}
        else{sum += pCount}

        if sum > 1000000000 { return -1}
    }
    return sum
}

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

댓글