Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] 자연수 뒤집어 배열로 만들기 #64

Closed
hwangJi-dev opened this issue Jan 10, 2023 · 0 comments
Closed

[Algorithm] 자연수 뒤집어 배열로 만들기 #64

hwangJi-dev opened this issue Jan 10, 2023 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Jan 10, 2023

💬 문제

[코딩테스트 연습 - 자연수 뒤집어 배열로 만들기](https://school.programmers.co.kr/learn/courses/30/lessons/12932)


💬 풀이

func solution(_ n:Int64) -> [Int] {
    return Array(String(n)).reversed().map({ Int(String($0))! })
}

💬 알게된 문법

✅ compactMap

  • 시퀀스의 각 요소를 transform한 결과들 중 nil이 아닌 것들만 반환한다.
return Array(String(n)).reversed().compactMap({ Int(String($0)) })
// [5, 4, 3, 2, 1]

// map과 비교 -> map은 강제 언래핑 또는 옵셔널 바인딩을 해주어야 한다.
return Array(String(n)).reversed().map({ Int(String($0))! })
// ✅ [ map과 비교 ]
let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5] (map은 nil을 포함함)

let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5] (compactMap은 nil을 제외)
  • 배열에서 nil을 제거하고 옵셔널 바인딩을 하고싶다면 compactMap을 사용하자!
  • 시간복잡도: O(m+n)

https://developer.apple.com/documentation/swift/sequence/compactmap(_:)


✅ flatMap

  • 시퀀스의 각 요소를 transform한 결과들을 연결하여 반환한다.
  • 2차원 배열 → 1차원 배열로 flat하고 싶을 때 사용하자!
let numbers = [1, 2, 3, 4]

let mapped = numbers.map { Array(repeating: $0, count: $0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
  • 시간복잡도: O(m+n)

https://developer.apple.com/documentation/swift/sequence/flatmap(_:)-jo2y

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant