【发布时间】:2015-07-23 15:39:26
【问题描述】:
今天我接受了关于 Scala 的采访,要求是:
使用以下功能实现具有固定大小 N 的数据结构:
- 获取(索引)
- 设置(索引,值)
- 设置(值)
复杂度应该是 O(1)
example:
val ds = DS(100)
ds.set(4,5)
ds.get(4) //would return 5
ds.set(1,4)
ds.setall(10)
ds.get(4) //would return 10
ds.get(7) //would return 10
ds.set(1,7)
ds.get(1) //would return 7
请在下面找到我发送的代码。
我的问题是这是正确的解决方案吗?是否有更好的方法?
import scala.collection.mutable.HashMap
trait Operations {
def get(index: Int): Int
def set(index: Int, value: Int)
def setall(value: Int)
}
class DS(N: Int) extends Operations {
var myMutableHashMap = new HashMap[Int, Int]().withDefaultValue(0)
def get(index: Int) = myMutableHashMap(index)
def set(index: Int, value: Int) = {
if (index <= N) myMutableHashMap += (index -> value)
}
def setall(value: Int) = {
myMutableHashMap = new HashMap[Int, Int]().withDefaultValue(value)
}
}
object Task {
def main(args: Array[String]): Unit = {
val ds = new DS(100)
ds.set(4, 5)
ds.get(4)
println(ds.get(4)) // -> 5
ds.setall(10)
println(ds.get(4)) //-> 10
println(ds.get(7)) //-> 10
ds.set(1, 7)
println(ds.get(1)) //-> 7
}
}
【问题讨论】:
标签: scala data-structures