Algorithm

Codility - Distinct

GREEN.1229 2021. 10. 17. 08:45
요즘 알고리즘을 도통 안한것 같아서..
사실 할 필요성을 크게 못느끼고 있었던것도 있다😱
그래서 알고리즘 학습이나 문제 풀이를 예전보다 낮은 비중으로 두기로 하였지만
주말에는 딥한거 하기가 싫어서 정말 간단하게 쉬운걸로 머리를 깨우려고 심심해서 풀어보는 문제!

아래 문제는 코딜리티에서 제공하는 Sorting > distinct의 문제입니다🧑🏻‍💻

 

문제 제시

Write a function
public func solution(_ A : inout [Int]) -> Int
that, given an array A consisting of N integers, returns the number of distinct values in array A.
For example, given array A consisting of six elements such that:
A[0] = 2 A[1] = 1 A[2] = 1 A[3] = 2 A[4] = 3 A[5] = 1

the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [0..100,000];each element of array A is an integer within the range [−1,000,000..1,000,000].

문제 해결

import Foundation
import Glibc

public func solution(_ A : inout [Int]) -> Int {
    return Set(A).count
}

 

사용된 개념

 - Set

 

문제 뒷담화

너..무..쉽....

오랜만에 풀어서 너무 가벼운 문제로 머리를 깨웠나..?

(코딜리티 레슨을 기냥 위에서 부터 순서대로 풀고 있어서 난이도는 항상 케바케..)

해당 문제의 카테고리가 왜 Sorting인지 잘 모르겠다.

아마 Set을 쓰지 않고 풀이를 했으면 A를 받아와 오름차순으로 정렬시키고 반복을 통해서

요소들의 같음과 다름을 판별하여 별도의 count 변수를 리턴하게 했을것 같다.

그치만 아주 좋은 Set이라는게 있기 때문에..

Set은 중복요소들을 허용해주지 않는다!

그렇기에 그냥 받아온 A를 Set 타입으로 만들어주고 담겨있는 요소의 수를 반환해주면 끝..이지..

 

[참고자료]

https://app.codility.com/c/run/training3J266N-TT5/

 

Codility

Your browser is not supported You should use a supported browser. Read more

app.codility.com