
#1 런타임에러
import Foundation let t = Int(readLine()!)! for _ in 0...t { let n = Int(readLine()!)! let nums = readLine()!.split(separator: " ").map{Int($0)!} print(solution(n: n, nums: nums)) } func solution(n: Int, nums: [Int]) -> String { let temp = nums.sorted() return "\\(temp[0]) \\(temp[n - 1])" }
t - 1을 안해줘서 한 줄을 더 받고 있었다..
하지만 고쳤는데 시간 초과 ㅠ
역시 sorted는 안되려나
#2 시간초과
import Foundation let t = Int(readLine()!)! for _ in 0...t - 1 { let n = Int(readLine()!)! let nums = readLine()!.split(separator: " ").map{Int($0)!} print("\\(nums.min()!) \\(nums.max()!)") }
sorted → O(nlogn)
min(), max() → O(n)
#3 시간초과…
import Foundation let t = Int(readLine()!)! for _ in 0...t - 1 { let n = Int(readLine()!)! let nums = readLine()!.split(separator: " ").map{Int($0)!} var max = -1000001 var min = 1000001 nums.forEach { item in if item > max { max = item } if item < min { min = item } } print("\\(min) \\(max)") }
왜 이것도 안되는거지
ㅠㅠ 파이썬으로 했으면 성공할 코든데!! 왜 시간초과가 가는걸까
#4 맞았습니다!!
Swift 언어 시간초과 관련 질문게시판 돌아다니다가 발견한 빠른 입출력!!!
ps할 때 입력을 한꺼번에 받기 위한 유틸리티 클래스. fread의 swift 버전.
https://gist.github.com/JCSooHwanCho/30be4b669321e7a135b84a1e9b075f88
시간초과의 주범은 readline이었다
위 코드를 파일 위에 추가하고 제출하니 통과!!
import Foundation final class FileIO { private let buffer:[UInt8] private var index: Int = 0 init(fileHandle: FileHandle = FileHandle.standardInput) { buffer = Array(try! fileHandle.readToEnd()!)+[UInt8(0)] // 인덱스 범위 넘어가는 것 방지 } @inline(__always) private func read() -> UInt8 { defer { index += 1 } return buffer[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 now = read() while now == 10 || now == 32 { now = read() } // 공백과 줄바꿈 무시 let beginIndex = index-1 while now != 10, now != 32, now != 0 { now = read() } return String(bytes: Array(buffer[beginIndex..<(index-1)]), encoding: .ascii)! } @inline(__always) func readByteSequenceWithoutSpaceAndLineFeed() -> [UInt8] { var now = read() while now == 10 || now == 32 { now = read() } // 공백과 줄바꿈 무시 let beginIndex = index-1 while now != 10, now != 32, now != 0 { now = read() } return Array(buffer[beginIndex..<(index-1)]) } } let fIO = FileIO() let t = fIO.readInt() for _ in 0...t - 1 { let n = fIO.readInt() var nums: [Int] = [] for _ in 0...n - 1 { nums.append(fIO.readInt()) } var max = -1000001 var min = 1000001 nums.forEach { item in if item > max { max = item } if item < min { min = item } } print(min, max) }
'공부하자! > 알고리즘' 카테고리의 다른 글
백준 1913 달팽이 Swift - 구현 (0) | 2023.05.23 |
---|---|
백준 20546 기적의 매매법 Swift - 구현 (0) | 2023.05.23 |
프로그래머스 | 영어 끝말잇기 Lv.2 Swift (0) | 2023.03.17 |
프로그래머스 | 방문 길이 Lv.2 Swift (0) | 2023.03.17 |
프로그래머스 | 전화번호 목록 Lv.2 (0) | 2023.03.06 |