문제 : https://programmers.co.kr/learn/courses/30/lessons/42842
풀이방법
- brown + yellow의 수의 모든 약수를 완전탐색으로 알아냄
- count가 홀수 일때는 중간 약수 값을 리턴함 [중간약수, 중간약수]
- count가 짝수 일때는 노란색 수가 맞는지 일단 확인한다. <중요!! 아니면 테스트 4,6,7 실패함>
- 노란색 수를 구하는 식은 테두리가 모두 갈색이므로
- 노란색 수 = (카펫 가로길이 - 2) * (카펫 세로길이 - 2 ) 확인 후 같으면 해당하는 약수를 배열에 담아서 리턴 함
- 안같으면 다음 인덱스로 이동한다.
코드
import Foundation
func solution(_ brown:Int, _ yellow:Int) -> [Int] {
var measures = [Int]()
let sum = brown + yellow
let midIndex = measures.count / 2
//sum의 모든 약수 뽑아내기
for measure in 1...sum {
if sum % measure == 0 {
measures.append(measure)
}
}
if measures.count % 2 == 0 {
var index = 0
while true {
//노란색 갯수 확인하기
let yellowCount = (measures[midIndex + index] - 2) * (measures[midIndex - 1 - index] - 2)
if yellow == yellowCount {
return [measures[midIndex + index], measures[midIndex - 1 - index]]
} else {
index += 1
}
}
} else {
return [measures[midIndex], measures[midIndex]]
}
return []
}
반응형
'알고리즘' 카테고리의 다른 글
[해쉬] Group -anagrams - LeetCode Swift (0) | 2021.07.28 |
---|---|
[LinkedList] remove-nth-node-from-end-of-list - LeetCode Swift (0) | 2021.07.23 |
[DFS] Sum Root To Leaf Numbers - LeetCode Swift (0) | 2021.07.22 |
[정렬] 병합정렬 Swift (0) | 2021.07.20 |
[정렬] H-Index 프로그래머스 Swift (0) | 2021.07.19 |