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

[Swift] Codility Lesson 3 - PermMissingElem

by hyebin (Helia) 2022. 7. 23.
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

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๊ฐ€ ๋ฐฐ์—ด์— ์—†๋‹ค.

 

ํ•ด๊ฒฐ๋ฐฉ์•ˆ

  1. ๋ฐฐ์—ด A๋ฅผ Set(์ง‘ํ•ฉ)์œผ๋กœ ๋ณ€ํ™˜
  2. 1๋ถ€ํ„ฐ N+1๊นŒ์ง€์˜ ์ •์ˆ˜๋“ค๋กœ ๊ตฌ์„ฑ๋œ Set์„ ์ƒ์„ฑ
  3. ๋‘˜์˜ ์ฐจ์ง‘ํ•ฉ์„ ๊ณ„์‚ฐ (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