Skip to content

Instantly share code, notes, and snippets.

@maowug
Created September 26, 2016 06:28
Show Gist options
  • Save maowug/f589e43f1a79baf3e35df5316cf7b498 to your computer and use it in GitHub Desktop.
Save maowug/f589e43f1a79baf3e35df5316cf7b498 to your computer and use it in GitHub Desktop.
`withFilter` rocks when used as a flag & something like short circulating
def anyDuplicate(arr: List[Int], k: Int): Boolean = {
var any_duplicate = false
val hs = mutable.HashSet[(Int, Int)]()
arr.zipWithIndex
.withFilter(_ => !any_duplicate)
.map {
case tp @ (e, idx) =>
hs.find(_._1 == tp._1) match {
case Some((d, idxD)) if (tp._2 - idxD <= k) =>
any_duplicate = true // <-------- update flag
case Some(_) => ()
case None =>
hs.add(tp)
}
}
any_duplicate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment