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

[Swift] Codility Lesson 4 - PermCheck

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

๋ฌธ์ œ

A non-empty array A consisting of N integers is given.

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. 1๋ถ€ํ„ฐ N๊นŒ์ง€์˜ ์ •์ˆ˜๋“ค์„ ๊ฐ’์œผ๋กœ ๊ฐ–๋Š” Set(์ง‘ํ•ฉ) ์ƒ์„ฑ
  2. 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