gpt4 book ai didi

Scala 数据结构和复杂度 O(1)

转载 作者:行者123 更新时间:2023-12-02 03:23:33 25 4
gpt4 key购买 nike

今天我接受了关于 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

}

}

最佳答案

我不确定它是否更好,但我认为 HashMap 可能有点矫枉过正。以下解决方案可能占用空间更小,代码更少。虽然,我可能宁愿实现更通用的东西,但它应该满足您提到的要求。

trait Operations {
def get(index: Int): Int
def set(index: Int, value: Int): Unit
def setall(fill: Int): Unit
}

class DS(size: Int) extends Operations {
val underlying: Array[Int] = new Array(size)

def get(index: Int): Int = underlying(index)

def set(index: Int, value: Int): Unit = underlying(index) = value

def setall(fill: Int): Unit = (0 until size).foreach(underlying(_) = fill)
}

替代方案,这可能会给我们带来更好的“setall”复杂性,但要付出代价......

trait Operations {
def get(index: Int): Int
def set(index: Int, value: Int): Unit
def setall(fill: Int): Unit
}

class DS(size: Int) extends Operations {
var underlying: Array[Integer] = new Array(size)
var default: Integer = new Integer(0)

def get(index: Int): Int = {
val result = underlying(index)
if (result == null) default else result
}

def set(index: Int, value: Int): Unit = underlying(index) = value

def setall(fill: Int): Unit = {
default = fill
underlying = new Array(size)
}
}

关于Scala 数据结构和复杂度 O(1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31592053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com