-
Notifications
You must be signed in to change notification settings - Fork 3
/
좌표 압축.swift
45 lines (36 loc) · 1.07 KB
/
좌표 압축.swift
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import Foundation
let n = Int(readLine()!)!
var arr = readLine()!.split(separator: " ").map{ Int(String($0))! }
func solution(n: Int, arr: [Int]) -> [Int] {
let sortedArr = arr.removeDuplicates().sorted()
var dict: Dictionary<Int, Int> = [:]
var result: [Int] = []
arr.forEach {
if let alreadyChecked = dict[$0] {
result.append(alreadyChecked)
return
}
var low = 0
var high = sortedArr.count - 1
while low <= high {
let mid = (low + high) / 2
if $0 > sortedArr[mid] {
low = mid + 1
} else {
high = mid - 1
}
}
dict.updateValue(low, forKey: $0)
result.append(low)
}
return result
}
solution(n: n, arr: arr).forEach {
print($0, terminator: " ")
}
extension Array where Element: Hashable {
func removeDuplicates() -> [Element] {
var dict: Dictionary<Element, Bool> = [:]
return filter{ dict.updateValue(true, forKey: $0) == nil }
}
}