在Scala中排序和删除性能

时间:2017-11-23 02:13:36

标签: scala

我正在编写一个程序,用于确定如果删除了一个且只有一个元素,则数组是否会严格按顺序递增。它工作但显然它没有通过codefights设置的时间限制(要清楚它在我的本地机器上运行,并且在他们的服务器上失败了30秒的时间限制(数组中有5000个数字))。

哪种操作性能最高? Sort只运行一次,每次迭代运行的唯一操作是修补数组,删除由array diff和distinct定义的值。感谢。

def remove(num: Int, array: Array[Int]): Array[Int] = array diff Array(num)

def almostIncreasingSequence(sequence: Array[Int]): Boolean = {
    var i = 0
    val sortedSequence = sequence.sortWith(_ < _)
    while (i < sequence.length) {
        val patchedSequence = sequence.patch(i, Nil, 1)
        if(patchedSequence.sameElements(remove(sequence(i), sortedSequence).distinct)) return true
        i += 1
    }
    return false
}

1 个答案:

答案 0 :(得分:1)

所以这些东西的诀窍是通常避免排序(如果可能)并且只遍历一次。也许是这样的。

def almostIncreasingSequence(sequence: Array[Int]): Boolean = {
  sequence.indices.tail.filter(x => sequence(x-1) >= sequence(x)) match {
    case Seq(x) => x == 1 ||                       //remove sequence.head
                   sequence(x-2) < sequence(x) ||  //remove sequence(x-1)
                   !sequence.isDefinedAt(x+1) ||   //remove sequence.last
                   sequence(x-1) < sequence(x+1)   //remove sequence(x)
    case Seq() => true  //no dips in sequence
    case _ => false     //too many dips in sequence
  }
}