전체 글54 [프로그래머스] Lv.2 N개의 최소공배수 1. arr를 순회하면서 누적적으로 최소공배수를 구하기 위해 for 문을 사용했는데, reduce를 사용해볼 수도 있다. 고차함수의 활용은 종말 간편하다.. func solution(_ arr:[Int]) -> Int { func gcd(_ a: Int, _ b: Int) -> Int { if b == 0 { return a } return gcd(b, a % b) } func lcm(_ a: Int, _ b: Int) -> Int { return a * b / gcd(a, b) } var result = arr[0] for i in arr { result = lcm(result, i) } return result } arr.reduce(1) { lcm($0, $1) } 2024. 4. 11. [프로그래머스] Lv.2 귤 고르기 문제 1. 배열의 요소의 갯수를 카운트 해야했다. for 문을 이용했는데, Dictionary 그룹핑을 이용하는 방법도 있다. func solution(_ k:Int, _ tangerine:[Int]) -> Int { var dict = [Int: Int]() var sum = 0 var ans = 0 for i in tangerine { if dict[i] == nil { dict[i] = 1 } else { dict[i]! += 1 } } for i in dict.values.sorted(by: >) { sum += i ans += 1 if sum >= k { break } } return ans } Dictionary(grouping: tangerine) { $0 }.values.sorted { $0.c.. 2024. 4. 11. [프로그래머스] Lv.2 행렬의 곱셈 문제 1. 두번째 행렬의 전치행렬을 구해야겠다는 것이 처음 아이디어였다. 시도는 좋았으나 코드 가독성이 떨어지고 그닥 직관적이지 않다. func solution(_ arr1:[[Int]], _ arr2:[[Int]]) -> [[Int]] { var newArr = [[Int]]() for i in 0.. [[Int]] { var result = [[Int]](repeating: [Int](repeating: 0, count: arr2[0].count), count: arr1.count) for i in 0.. 2024. 4. 11. [240401] Dictionary(grouping:by:)/if let과 guard let 1. 여전히 푸는데 오래 걸리지만.. 전에 풀었던 문제에서 활용할 수 있는 풀이가 한두개씩 떠오르기 시작했다 이번에는 딕셔너리 그루핑을 사용해봤는데 아주 뿌듷사다! func solution(_ id_list:[String], _ report:[String], _ k:Int) -> [Int] { var arr = Set(report).map { $0.split(separator: " ").map { String($0) } } var dict = Dictionary(grouping: arr) { $0.last } var idDict: [String: Int] = [:] for id in id_list { idDict[id] = 0 } for r in dict { if r.value.count >= k { f.. 2024. 4. 1. 이전 1 ··· 4 5 6 7 8 9 10 ··· 14 다음