yeahg-dev / algorithm Goto Github PK
View Code? Open in Web Editor NEW알고리즘, 자료구조와 친해지기
알고리즘, 자료구조와 친해지기
실패율을 구하기 위해 아래와 같이 stage
를 순회하면서 각 stage에 대한 실패율을 계산한 배열을 리턴했다.
func solution(_ N:Int, _ stages:[Int]) -> [Int] {
// 각 스테이지에 대한 실패율 계산
// 스테이지 == 유저/유저 <= 스테이지
let stageContainer: [Int] = Array(1...N)
let result: [(Int, Double)] = stageContainer.map{(stage: Int) -> (Int, Double) in
let plyersYetClear: Int = stages.filter{$0 == stage}.count
let playersOnStage: Int = stages.filter{$0 >= stage}.count
if playersOnStage == 0 {
return (stage, 0)
}
let failureRate = Double(plyersYetClear) / Double(playersOnStage)
return (stage, failureRate)
}
// 실패율 높은 스테이지부터 sort
let stageResult = result.sorted{
if $0.1 != $1.1 {
return $0.1 > $1.1
}
return $0.0 < $1.0}.map{$0.0}
return stageResult
}
실행 결과, 몇 개의 테스트에서 시간초과
가 발생했다.
고민끝에 구글링을 하다가 https://keeplo.tistory.com/160 을 발견하게되었고,
stageContainer
를 map으로 순회하면서 내부에서 또 stages
를 순회해서 발생하는 문제임을 파악했다.
스테이지의 개수 N은 1 이상 500 이하의 자연수이다.
stages의 길이는 1 이상 200,000 이하이다.
위와 같은 조건에서 최악의 경우 스테이지개수 * stages의 길이는 500 * 200,000 로 매우 크다.
따라서 stages
를 단 한번 순회하면서 실패율을 계산하는 로직으로 수정했다.
func solution(_ N:Int, _ stages:[Int]) -> [Int] {
var stageRate: [Int] = [Int](repeating: 0, count: N + 1)
for stage in stages {
for i in 0..<stage {
stageRate[i] += 1
}
}
var result = [Int: Double]()
for i in 0..<N {
if Double(stageRate[i]) == 0 {
result.updateValue(0, forKey:i+1)
continue
}
let rate = Double(stageRate[i] - stageRate[i+1]) / Double(stageRate[i])
result.updateValue(rate, forKey:i+1)
}
// 실패율 높은 스테이지부터 sort
let stageResult = result.sorted{
if $0.1 != $1.1 {
return $0.1 > $1.1
}
return $0.0 < $1.0}.map{$0.0}
return stageResult
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.