백준_1654_binary search(2회독)

hankyulee·2021년 12월 27일
0

Swift coding test 준비

목록 보기
50/57

1회독

import Foundation
let given = readLine()!.split(separator: " ").map{Int($0)!}
let n = given[0]
let m = given[1]
var have : [Int] = []

for _ in 0..<n{
    let k = Int(readLine()!)!
    have.append(k)
}

func upperBound(targetN:Int)->Int{
    var startN = 1
    var endN = Int(pow(2.0, 31)-1)
    while(startN<=endN){
        let mid = ( startN + endN ) / 2
        var total = 0
        for i in have {
            total += i / mid
        }
        if total < targetN {
            endN = mid - 1//작게썰자
        }
        else if total >= targetN {
            startN = mid + 1//크게썰자
        }
    }
    return endN
}
print(upperBound(targetN: m))

2회독

import Foundation

let numbers = readLine()!.split(separator: " ").map{Int($0)}
var myThings:[Int] = []
let mine = (numbers[0])!
let need = numbers[1]!
for _ in 0..<mine {
    let given = Int(readLine()!)!
    myThings.append(given)
}

func checkNumbers(_ line : Int) -> Int{
    var result: Int = 0
    for i in myThings {
        result += (i / line)
    }
    return result
}

func binary_search(array:[Int],target:Int,start:Int,end:Int)->Int {
    var start = start
    var end = end
    while start <= end {
        let mid = (start + end) / 2
        if checkNumbers(mid) >= target {
            start = mid + 1
        }
        else {
            end = mid - 1
        }
    }
    return end
}


let k = binary_search(array: myThings, target: need, start: 0, end: Int(pow(2.0,31))-1)
print(k)

0개의 댓글