๋ฌธ์
An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
Your goal is to find that missing element.
Write a function:
public func solution(_ A : inout [Int]) -> Int
that, given an array A, returns the value of the missing element.
For example, given array A such that:
A[0] = 2, A[1] = 3, A[2] = 1, A[3] = 5
the function should return 4, as it is the missing element.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [0..100,000];
the elements of A are all distinct;
each element of array A is an integer within the range [1..(N + 1)].
๋งํฌ
PermMissingElem coding task - Learn to Code - Codility
Find the missing element in a given permutation.
app.codility.com
๋ฌธ์ ๋ถ์
- ์ ์ N๊ฐ๋ก ๊ตฌ์ฑ๋ ๋ฐฐ์ด A๊ฐ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ค.
- ๋ฐฐ์ด A๋ 1๋ถํฐ N+1๊น์ง์ ๋ฒ์์ ์ ์๋ค๋ก ๊ตฌ์ฑ๋๋ค.
- 1๋ถํฐ N+1๊น์ง์ ๋ฒ์์ ์ ์๋ค ์ค ๋ฐฐ์ด์ ์๋ ์์๋ฅผ ์ฐพ์ ๋ฐํํ๋ค.
ex) A = [1, 6, 3, 5, 2]
N = 5
1๋ถํฐ 6๊น์ง ๋ฒ์์ ์ ์๋ค ์ค 4๊ฐ ๋ฐฐ์ด์ ์๋ค.
ํด๊ฒฐ๋ฐฉ์
- ๋ฐฐ์ด A๋ฅผ Set(์งํฉ)์ผ๋ก ๋ณํ
- 1๋ถํฐ N+1๊น์ง์ ์ ์๋ค๋ก ๊ตฌ์ฑ๋ Set์ ์์ฑ
- ๋์ ์ฐจ์งํฉ์ ๊ณ์ฐ (substracting)
Solution
public func solution(_ A : inout [Int]) -> Int {
let setA = Set(A)
let setB = Set(1...(A.count+1))
return setB.subtracting(setA).first!
}
- ์๊ฐ ๋ณต์ก๋: O(N) or O(N * log(N))
'โจ๏ธ Language > swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] Codility Lesson 4 - FrogRiverOne (0) | 2022.07.23 |
---|---|
[Swift] Codility Lesson 3 - TapeEquilibrium (0) | 2022.07.23 |
[Swift] Codility Lesson 3 - FrogJmp (0) | 2022.07.23 |
[Swift] Codility Lesson 2 - OddOccurrencesInArray (0) | 2022.07.23 |
[Swift] Codility Lesson2 - CyclicRotation (0) | 2022.07.23 |