Scala 2.11.4 - While trying to solve this problem "Sliding Window Maximum", I wrote this code :
def slidingMaximum(A: Array[Int], B: Int): Array[Int] = {
var ans = Vector[Int]()
var vectorQ = Vector[Int]()
for (i <- 0 to A.length-1) {
if (vectorQ.isEmpty) {
vectorQ = vectorQ :+ i
}else{
while (!vectorQ.isEmpty && A(vectorQ.last) <= A(i))
vectorQ = vectorQ.dropRight(1)
while (!vectorQ.isEmpty && (vectorQ.head <= i-B))
vectorQ = vectorQ.drop(1)
vectorQ = vectorQ :+ i
}
if (i+1 >= B) ans = ans :+ A(vectorQ.head);
}
return ans.toArray;
}
Since, I am a beginner in Scala Language, I used this suggestion for using Vector
as Deque. When I tried replacing Vector
type with Array
or ArrayBuffer
, the test cases failed for poor time complexity. Why can't we have var ans = ArrayBuffer[Int]()
or var ans = Array[Int]()
when it is mostly involved in append operation using :+
?
What makes Vector
really standout?