๋ฌธ์
A non-empty array A consisting of N integers is given.
A permutation is a sequence containing each element from 1 to N once, and only once.
For example, array A such that:
A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2
is a permutation, but array A such that:
A[0] = 4 A[1] = 1 A[2] = 3
is not a permutation, because value 2 is missing.
The goal is to check whether array A is a permutation.
Write a function:
public func solution(_ A : inout [Int]) -> Int
that, given an array A, returns 1 if array A is a permutation and 0 if it is not.
For example, given array A such that:
A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2
the function should return 1.
Given array A such that:
A[0] = 4 A[1] = 1 A[2] = 3
the function should return 0.
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 within the range [1..1,000,000,000].
๋ฌธ์ ๋งํฌ
PermCheck coding task - Learn to Code - Codility
Check whether array A is a permutation.
app.codility.com
GitHub
GitHub - yoohyebin/swift
Contribute to yoohyebin/swift development by creating an account on GitHub.
github.com
๋ฌธ์ ๋ถ์
- N๊ฐ์ ์ ์๋ก ๊ตฌ์ฑ๋ ๋ฐฐ์ด A๊ฐ ์์ด์ธ์ง ์๋์ง ํ๋จํ๋ ๋ฌธ์ ์ด๋ค.
- ๋ฐฐ์ด A๊ฐ ์์ด์ด๋ผ๋ฉด 1, ์๋๋ผ๋ฉด 0์ ๋ฐํํ๋ค.
- ์ด๋ฒ ๋ฌธ์ ์์๋ 1๋ถํฐ N๊น์ง์ ์ ์๋ฅผ 1๊ฐ์ฉ ๋ชจ๋ ๊ฐ๊ณ ์๋์ง ํ๋จํด์ผ ํ๋ค.
์์ด: ์๋ก ๋ค๋ฅธ n๊ฐ์ ์์์์ r๊ฐ๋ฅผ ์ค๋ณต ์์ด ์์์ ์๊ด์๊ฒ ์ ํํ๋ ํน์ ๋์ดํ๋ ๊ฒ
ํด๊ฒฐ ๋ฐฉ์
- 1๋ถํฐ N๊น์ง์ ์ ์๋ค์ ๊ฐ์ผ๋ก ๊ฐ๋ Set(์งํฉ) ์์ฑ
- Set๊ณผ ๋ฐฐ์ด A์ ์ฐจ์งํฉ์ ๊ณ์ฐ
- ์ฐจ์งํฉ์ด ์๋ค๋ฉด ์์ด์ด ์๋๊ธฐ ๋๋ฌธ์ 0 ๋ฐํ
- ์ฐจ์งํฉ์ด ์๋ค๋ฉด ์์ด์ด ๋ง๊ธฐ ๋๋ฌธ์ 1 ๋ฐํ
Solution
public func solution(_ A : inout [Int]) -> Int {
let setB = Set(1...A.count)
return setB.subtracting(A).isEmpty ? 1 : 0
}
- ์๊ฐ ๋ณต์ก๋: O(N) or O(N * log(N))
'โจ๏ธ Language > swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] Codility Lesson 4 - MissingInteger (0) | 2022.07.24 |
---|---|
[Swift] Codility Lesson 4 - MaxCounters (0) | 2022.07.23 |
[Swift] Codility Lesson 4 - FrogRiverOne (0) | 2022.07.23 |
[Swift] Codility Lesson 3 - TapeEquilibrium (0) | 2022.07.23 |
[Swift] Codility Lesson 3 - PermMissingElem (0) | 2022.07.23 |