[LeetCode/Scala] 第187场周赛总结

这次周赛题目比较简单,就贴一下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
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值