๋ฌธ์
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 >
ํด๊ฒฐ๋ฐฉ์
- ๋์ชฝ์ผ๋ก ๊ฐ๋ ์ฐจ (A [i] = 0)๊ฐ ๋์ด๋ ๋๋ง๋ค pCount ๊ฐ์ ์ฆ๊ฐ
- ์์ชฝ์ผ๋ก ๊ฐ๋ ์ฐจ๊ฐ ์์ ๋๋ง๋ค 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)
'โจ๏ธ Language > swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ํ๋ก๊ทธ๋๋จธ์ค LV.0 ์ค๋ณต๋ ์ซ์ ๊ฐ์ (0) | 2022.11.29 |
---|---|
[Swift] Codility Lesson 5 - CountDiv (0) | 2022.07.26 |
[Swift] Codility Lesson 4 - MissingInteger (0) | 2022.07.24 |
[Swift] Codility Lesson 4 - MaxCounters (0) | 2022.07.23 |
[Swift] Codility Lesson 4 - PermCheck (0) | 2022.07.23 |