1920 수 찾기 + FileIO 사용

Choong Won, Seo·2021년 12월 28일
0

백준

목록 보기
7/28
post-thumbnail

Today 12/27

수 찾기 (My Code)

let N = Int(readLine()!)!
let numArr = readLine()!.split(separator: " ").map{Int(String($0))!}.sorted(by: <)
let M = Int(readLine()!)!
let inputArr = readLine()!.split(separator: " ").map{Int(String($0))!}

for input in inputArr {
    var min = 0
    var max = N-1
    while min <= max {
        let mid = (min+max) / 2
        if input == numArr[mid] {
            print("1")
            break
        } else if input < numArr[mid] {
            max = mid - 1
        } else {
            min = mid + 1
        }
    }
    if min > max {
        print("0")
    }
}

처음에는 .contains()를 써서 쉽게 가려했지만 아니나 다를까 시간초과가 되었다.

이전에 썻었던 이진 탐색을 써서 문제를 해결했다.

input을 받는 과정에서 시간이 많이 걸리는 것 같아, 그리고 다른 분들의 답안을 보았을 때, 라이노님의 FileIO를 많이 쓰셔서 이 기회에 써보기로 했다.

수 찾기 (Others Code)

// 라이노님의 FileIO
final class FileIO {
    private var buffer:[UInt8]
    private var index: Int
    
    init(fileHandle: FileHandle = FileHandle.standardInput) {
        buffer = Array(fileHandle.readDataToEndOfFile())+[UInt8(0)] // 인덱스 범위 넘어가는 것 방지
        index = 0
    }
    
    @inline(__always) private func read() -> UInt8 {
        defer { index += 1 }
        
        return buffer.withUnsafeBufferPointer { $0[index] }
    }
    
    @inline(__always) func readInt() -> Int {
        var sum = 0
        var now = read()
        var isPositive = true
        
        while now == 10
                || now == 32 { now = read() } // 공백과 줄바꿈 무시
        if now == 45{ isPositive.toggle(); now = read() } // 음수 처리
        while now >= 48, now <= 57 {
            sum = sum * 10 + Int(now-48)
            now = read()
        }
        
        return sum * (isPositive ? 1:-1)
    }
    
    @inline(__always) func readString() -> String {
        var str = ""
        var now = read()
        
        while now == 10
                || now == 32 { now = read() } // 공백과 줄바꿈 무시
        
        while now != 10
                && now != 32 && now != 0 {
            str += String(bytes: [now], encoding: .ascii)!
            now = read()
        }
        
        return str
    }
}

let file = FileIO()
let N = file.readInt()
var numArr = Set<Int>()
for _ in 0..<N {
    numArr.insert(file.readInt())
}
let M = file.readInt()
var inputArr = [Int]()
for _ in 0..<M {
    inputArr.append(file.readInt())
}
var output = ""
inputArr.forEach { input in
    **output += numArr.contains(input) ? "1\n" : "0\n"**
}
print(output)

사용 방법은 처음에 file상수로 FileIO()를 받아주고, 단일 Int를 받을 때는 file.readInt(), 나누어진 Int 배열을 받을 때는 for문을 사용해서 받아서 넣어준다.

input에서 N개의 정수 부분에서 겹치는 숫자가 많은 것을 사람들이 발견했나보다. 그래서인지 Set으로 받아서 중복을 없애고 contains를 했더니 오히려 시간이 적게 나왔다.

Set에서는 append가 아니라 insert인 것을 기억하자.

print를 그 때 그 때 해주는 것이 아니라 3항연산자로 String에다가 문자를 추가하고 한 번에 print해 보자! (+= 사용)

profile
UXUI Design Based IOS Developer

0개의 댓글