看到有人用算法实现了在一个栈中实现最小值,且复杂度保持在O(1)的问题,用Scala实现看看是不是合适.
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 
 | import scala.collection.mutable.ArrayBuffer
 class MinStack {
 private val buffer = new ArrayBuffer[Int]()
 private val sort = new ArrayBuffer[Int]()
 
 def push(value: Int) :Unit = {
 buffer.append(value)
 val min = if(sort.length > 0) minValue() else 99999
 if(value < min){
 sort.append(buffer.length -1)
 }
 }
 
 def pop() :Int = {
 val pos = buffer.length - 1
 if(pos == sort.last){
 sort.remove(sort.length - 1)
 }
 buffer.remove(pos)
 }
 
 def minValue() :Int = {
 return if (sort.length > 0) buffer(sort.last) else 0
 }
 
 def description() : Unit = {
 println(buffer.mkString("(",",",")"))
 println(sort.mkString("(",",",")"))
 }
 }
 
 |