티스토리 뷰

SMALL

오늘의 문제

https://www.acmicpc.net/problem/18870

 

나의 풀이

let N = Int(readLine()!)!
var input = readLine()!.split(separator: " ").map { Int($0)! }

// Set으로 중복 제거 후 sorted로 오름차순 정렬
let setInput = Array(Set(input)).sorted()
// 딕셔너리 생성
// 계산된 값을 저장해두고 아는 값이면 꺼내서 바로 사용하기 위함
var dict = [Int: Int]()

// (인덱스, 값) 순서로 들어옴
for (index, num) in setInput.enumerated() {
    // 딕셔너리의 key로 '배열의 값'을 저장하고 딕셔너리의 value로 '그 값의 인덱스'를 저장한다
    dict[num] = index
}

// 인풋 하나씩 순회하면서
for num in input {
    // num을 딕셔너리의 key 값으로 넣어서 바로 그 숫자의 index 값 가져옴
    if let index = dict[num] {
        // 포맷에 맞게 출력
        print(index, terminator: " ")
    }
}

 

새로 알게 된 것

  • enumerated 함수
 

enumerated() | Apple Developer Documentation

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

developer.apple.com

  • enumerated 함수는 해당 배열의 각 element와 그 인덱스를 순회하는 함수이다.
  • enumerated 함수는 (n, x)의 튜플 형태를 return한다.
  • index에는 해당 숫자의 배열에서의 위치(index) 값이 들어가고,
  • value에는 그 숫자(value) 값이 들어간다.
LIST
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함