Counting bounded slice codility

后端 未结 7 1208
一个人的身影
一个人的身影 2021-02-08 13:11

I have recently attended a programming test in codility, and the question is to find the Number of bounded slice in an array..

I am just giving you breif explanation of

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 14:00

    I came up with a solution in Scala:

    package test
    import scala.collection.mutable.Queue
    
    object BoundedSlice {
    
      def apply(k:Int, a:Array[Int]):Int = {
        var c = 0
        var q:Queue[Int] = Queue()
        a.map(i => {           
          if(!q.isEmpty && Math.abs(i-q.last) > k) 
            q.clear
          else
            q = q.dropWhile(j => (Math.abs(i-j) > k)).toQueue      
          q += i
          c += q.length
        })
        c
      }
    
      def main(args: Array[String]): Unit = {
        val a = Array[Int](3,5,6,7,3)
        println(BoundedSlice(2, a))
      }
    }
    

提交回复
热议问题