[Programmers] 튜플 Swift

2023. 6. 19. 18:14🐣/Programmers

프로그래머스 튜플 Swift

내 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import Foundation
 
func solution(_ s:String-> [Int] {
    var dic = [Int:Int]()
    var result = [Int]()
    var input = s.replacingOccurrences(of: "{"with"")
    input = input.replacingOccurrences(of: "}"with"")
    var data = input.split{$0 == ","}.map{Int(String($0))!}
    for i in data {
        if dic[i] != nil {
            dic[i]! += 1
        } else {
            dic[i] = 1
        }
    }
    for (key, _) in dic.sorted(by: {$0.value > $1.value}) {
        result.append(key)
    }
    return result
}
 
 

 

다른 사람 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import Foundation
func solution(_ s:String-> [Int] {
    var s = s
    var answer = [Int]()
    s.removeFirst(2)
    s.removeLast(2)
 
    s.components(separatedBy: "},{")
        .map { $0.components(separatedBy: ",").map { Int($0)! } }
        .sorted { $0.count < $1.count }
        .forEach {
            $0.forEach {
                if !answer.contains($0) {
                    answer.append($0)
                }
            }
    }
    return answer
}