【发布时间】:2021-07-31 09:54:06
【问题描述】:
def getMax(operations: Array[String]): ArrayBuffer[Int] = {
// Write your code here
var a: ArrayBuffer[Int] = mutable.ArrayBuffer()
val s = mutable.Stack[Int]()
val check_1 = (s:String) => s.contains(" ") && (s.substring(0,1).toInt.equals(1))
val check_2 = (s:String) => (s.contains(" ") || !s.contains(" ")) && (s.substring(0,1).toInt.equals(2))
val check_3 = (s:String) => (s.contains(" ") || !s.contains(" ")) && (s.substring(0,1).toInt.equals(3))
val check_4 = (s:String) => s.substring(0,1).toInt.equals(1)
for(i <- operations) yield {
i match {
case w if(check_1(i)) => s.push(i.substring(2,(i.length)).toInt)
case d if(check_2(i)) => s.pop
case q if(check_3(i))=> a :+= s.max
case t if(check_4(i)) => s.push(i.substring(1,(i.length)).toInt)
case _ =>
}
}
a
}
和
def getMax(ops:Array[String]): Array[Int] ={
var a: Array[Int] = Array() // This is the cache for storing the max
val s = mutable.Stack[Int]()
for(i <- ops) {
if(i.contains(" ") && (i.substring(0,1).toInt.equals(1))) s.push(i.substring(2,(i.length)).toInt)
else if((i.contains(" ") || !i.contains(" ")) && (i.substring(0,1).toInt.equals(2))) s.pop
else if((i: .contains(" ") || !i.contains(" "))&& (i.substring(0,1).toInt.equals(3))) a :+= s.max
else if(i.substring(0,1).toInt.equals(1)) s.push(i.substring(1,(i.length)).toInt)
}
a
}
我尝试了这两种解决方案,它们都有 TLE(超过时间限制)。关于如何优化它的任何帮助? 问题链接:https://www.hackerrank.com/challenges/maximum-element/problem
【问题讨论】:
-
如果您在问题中描述问题会有所帮助。外部链接容易腐烂。
-
好的,会注意的