Last active
August 29, 2015 14:01
-
-
Save ericpony/5f363c295a178a82a03c to your computer and use it in GitHub Desktop.
Find the kth dominating members in an array in O(nk) time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Input: | |
* A: An integer seq containing at least one (A,k)-dominating element | |
* k: An integer >= 2 | |
* Output: | |
* An seq of (A,k)-dominating element(s) of A | |
*/ | |
def FindDominatingNumbers(s: Seq[Int], k: Int):Seq[Int] = { | |
require(k>=2 && s.length>=k) | |
var cand = new Array[Int](k - 1) | |
var cand_freq = new Array[Int](k - 1) | |
s foreach (a => breakable { | |
var i = -1; | |
while (true) { | |
i = i + 1 | |
if (i >= cand.length) { | |
cand.indices foreach (i => cand_freq(i) = cand_freq(i) - 1) | |
break | |
} | |
if (cand_freq(i) == 0) { | |
cand(i) = a | |
cand_freq(i) = 1 | |
break | |
} | |
if (cand(i) == a) { | |
cand_freq(i) = cand_freq(i) + 1 | |
break | |
} | |
} | |
}) | |
val threshold = cand_freq.sum / k | |
(cand zip cand_freq).view.filter(_._2 > threshold).map(_._1).force | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment