Swift Data Structure And Algorithm/Binary Search
2μ°¨μ μ λ΅ μΆμΈ‘
youngjaeLee1026
2022. 4. 2. 00:45
1. λ¬Έμ
2. μ μΆλ ₯
3. μ μΆλ ₯ μμ
4. λ¬Έμ μ€κ³
- μ«μ aμ μ΅λκ°μ 보면 19μ리 μ΄λ―λ‘, Int64 μλ£νμ μ μ₯ν΄μΌνλ κ²μ μ μ μμ
- f(x) = x ^ x + x 2μ°¨μμ κ³±μ ννλ‘ λ³ννκ² λλ©΄, f(x) = x * (x + 1)
- μ¦, μκΈ° μμ κ³Ό μμ λ³΄λ€ 1ν° μμ κ³±μ ν΅ν΄ aλ₯Ό λ§λ€μ΄λ΄μΌ λλ κ²μ μ μ μμ
- λ μμ κ³±μ ν΅ν΄ aλ₯Ό μ»μ΄λ΄μΌ νλ―λ‘, μμ νμμ νκ² λλ€λ©΄ O(N)μΌλ‘ λ¬Έμ λ₯Ό ν΄κ²°ν μ μμ
- λ°λΌμ μ΄μ§νμμ ν΅ν΄ 0λΆν° aμ μ κ³±κ·Ό + 1κΉμ§μ μλ₯Ό x * (x + 1) μ°μ° ν¨μΌλ‘μ¨ κ°μ μ»μ΄λΌ μ μμ
5. μ 체 μ½λ
//MARK: - 2μ°¨μ μ λ΅ μΆμΈ‘
//MARK: - Framework
import Foundation
//MARK: - Function
func binarySearch(_ start: Int64, _ end: Int64, _ value: Int64) -> Int64 {
if start + 1 >= end {
return start
}
let x: Int64 = (start + end) / 2
return x * (x + 1) <= value ? binarySearch(x, end, value) : binarySearch(start, x, value)
}
func solution() -> Void {
//MARK: - Input
guard let a: Int64 = Int64(readLine() ?? "0") else { return }
//MARK: - Process
let result: Int64 = binarySearch(0, Int64(sqrt(Double(a))) + 1, a)
//MARK: - Output
print(result)
}
solution()
μ 체μ½λλ μ¬κΈ°μμ νμΈν μ μμ΅λλ€.