알고리즘
[Swift 알고리즘] - 369게임 (Programmers)
Peppo
2022. 10. 26. 09:02
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/120891
문제 사진
내 풀이
import Foundation
func solution(_ order:Int) -> Int {
return String(order).filter { $0 == "3" || $0 == "6" || $0 == "9"}.count
}
solution(29423)
- [목표] 한줄로 끝내보자
- Int -> String 숫자 하나하나 3,6,9를 조회하기 위함
- filter로 3,6,9를 포함하고 있는것만 걸러내기
다른사람의 풀이
import Foundation
func solution(_ order:Int) -> Int {
return String(order).filter { "369".contains($0) }.count
}
이 방법이 조금 신기했다.
filter 내부에 "369" 문자열(배열)을 만들어 contains() 메서드로 조회하는 방법이 새로운 접근방법을 배울 수 있었다. 👍
배운것
contains(_:)
주어진 시퀀스에 지정된 요소가 '포함'되어 있으면 true 없으면 false를 반환합니다.
예제
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
print(cast.contains("Marlon"))
// Prints "true"
print(cast.contains("James"))
// Prints "false"
시간복잡도
O(n), where n is the length of the sequence.
728x90