【问题标题】:I am gettting TLE on Hackerrank how can I optimize the Scala code? I am trying to solve the maximum element problem on hackerrank我在 Hackerrank 上获得 TLE 如何优化 Scala 代码?我正在尝试解决hackerrank上的最大元素问题
【发布时间】: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

【问题讨论】:

  • 如果您在问题中描述问题会有所帮助。外部链接容易腐烂。
  • 好的,会注意的

标签: java scala jvm


【解决方案1】:

您需要维护堆栈中对象的有序列表以及堆栈本身。

这样你将有O(1) 复杂性来获取堆栈中的最大值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多