这次周赛题目比较简单,就贴一下code。 比赛时,后面两道题要用的二分搜索包bisect, 因为python自带,就直接上python了。 今天,自己实现了一下bisect这个包的几个函数,能做到
l
o
g
(
n
)
log(n)
log(n)的插入和搜索,不过insort
的不是insort_right
emm, 我做了一些改进,让函数名和python版的基本一致。这样方便记忆。
一: Bisect的scala实现, 用了ArrayBuffer, 以后可能会写成更通用的。看后面竞赛题,是不是有需要。
import scala.collection.mutable.{ArrayBuffer => MAB}
object Bisect {
type AB = MAB[Int]
def insort(ab:AB, x:Int):Unit = insort_right(ab, x)
def insort_right(ab: AB, x: Int): Unit = ab.insert(bisect(ab, x), x)
def insort_left(ab:AB, x:Int):Unit = ab.insert(bisect_left(ab,x))
def bisect(ab:AB, x:Int):Int = bisect_right(ab, x)
def bisect_right(ab: AB, x: Int): Int = bisect_right(ab, x, 0, ab.length)
def bisect_left(ab:AB, x:Int):Int = bisect_left(ab, x, 0, ab.length)
def bisect_left(ab: AB, target: Int, l: Int, r: Int): Int =
if (l >= r) l else {
val mid = l + (r - l) / 2
if (ab(mid) < target) bisect_right(ab, target, mid + 1, r)
else bisect_right(ab, target, l, mid)
}
def bisect_right(ab: AB, target: Int, l: Int, r: Int): Int =
if (l >= r) l else {
val mid = l + (r - l) / 2
if (ab(mid) <= target) bisect_right(ab, target, mid + 1, r)
else bisect_right(ab, target, l, mid)
}
def remove(ab: AB, x: Int): Unit = {
val idx = bisect(ab, x) - 1
if(ab(idx) == x) ab.remove(idx)
}
def find(ab: AB, x: Int): Int = {
val idx = bisect(ab, x) -1
if(ab(idx) == x) idx else -1
}
}
二, AC的代码
import scala.collection.mutable.ArrayBuffer
object C187 {
def destCity(paths: List[List[String]]): String = {
val src = paths.map(_.head)
(paths map {case List(a,b) => b} filterNot src.contains).head
}
def kLengthApart(nums: Array[Int], k: Int): Boolean = {
def f(l:List[Int]):Boolean = l match {
case Nil => true
case h::Nil => true
case i::j::t => if(j-i>=k+1) f(l.tail) else false
}
f(nums.zipWithIndex.filter(_._1==1).map(_._2).toList)
}
def longestSubarray(nums: Array[Int], limit: Int): Int = {
val A = ArrayBuffer[Int]();val n = nums.length
var l = 0; var ret = 0
for {r <- 0 until n} {
Bisect.insort(A, nums(r))
while(A.last - A.head > limit) {
A.remove(Bisect.search(A, nums(l)))
l+=1
}
ret = ret max (r-l+1)
}
ret
}
def kthSmallest(mat: Array[Array[Int]], k: Int): Int = {
var A = ArrayBuffer[Int]()
mat foreach {l =>
if(A.isEmpty) l foreach {x => Bisect.insort(A, x)}
else{
val B = ArrayBuffer[Int]()
for{x <- l; y <- A} Bisect.insort(B, x+y)
A = B
}
if(A.length > k) A = A.slice(0,k)
}
A.last
}
}