๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
โŒจ๏ธ Language/swift

[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)
๋ฐ˜์‘ํ˜•