fun countOccurrences(element: Int, array: List<Int>): Int {
var count = 0
for (el in array) {
if (el == element) {
count += 1
}
}
return count
}
fun findMajority(array: List<Int>): Int {
var counter = 0
var currentCandidate = 0
for (el in array) {
if(counter == 0) {
currentCandidate = el
counter = 1
} else if (el == currentCandidate) {
counter += 1
} else {
counter -= 1
}
}
if (countOccurrences(currentCandidate, array) >= array.count() / 2) {
return currentCandidate
} else {
return -1
}
}
fun main() {
val array = listOf(1, 2, 5, 5, 7, 5, 5, 10, 5, 5)
val majority = findMajority(array)
if (majority == -1) {
println("Nie ma lidera")
} else {
println("Lider to $majority")
}
}
ZnVuIGNvdW50T2NjdXJyZW5jZXMoZWxlbWVudDogSW50LCBhcnJheTogTGlzdDxJbnQ+KTogSW50IHsKICB2YXIgY291bnQgPSAwCgogIGZvciAoZWwgaW4gYXJyYXkpIHsKICAgIGlmIChlbCA9PSBlbGVtZW50KSB7CiAgICAgIGNvdW50ICs9IDEKICAgIH0KICB9CgogIHJldHVybiBjb3VudAp9CgpmdW4gZmluZE1ham9yaXR5KGFycmF5OiBMaXN0PEludD4pOiBJbnQgewogIHZhciBjb3VudGVyID0gMAogIHZhciBjdXJyZW50Q2FuZGlkYXRlID0gMAoKICBmb3IgKGVsIGluIGFycmF5KSB7CiAgICBpZihjb3VudGVyID09IDApIHsKICAgICAgY3VycmVudENhbmRpZGF0ZSA9IGVsCiAgICAgIGNvdW50ZXIgPSAxCiAgICB9IGVsc2UgaWYgKGVsID09IGN1cnJlbnRDYW5kaWRhdGUpIHsKICAgICAgY291bnRlciArPSAxCiAgICB9IGVsc2UgewogICAgICBjb3VudGVyIC09IDEKICAgIH0KICB9CgogIGlmIChjb3VudE9jY3VycmVuY2VzKGN1cnJlbnRDYW5kaWRhdGUsIGFycmF5KSA+PSBhcnJheS5jb3VudCgpIC8gMikgewogICAgcmV0dXJuIGN1cnJlbnRDYW5kaWRhdGUKICB9IGVsc2UgewogICAgcmV0dXJuIC0xCiAgfQp9CgpmdW4gbWFpbigpIHsKICB2YWwgYXJyYXkgPSBsaXN0T2YoMSwgMiwgNSwgNSwgNywgNSwgNSwgMTAsIDUsIDUpCgogIHZhbCBtYWpvcml0eSA9IGZpbmRNYWpvcml0eShhcnJheSkKCiAgaWYgKG1ham9yaXR5ID09IC0xKSB7CiAgICBwcmludGxuKCJOaWUgbWEgbGlkZXJhIikKICB9IGVsc2UgewogICAgcHJpbnRsbigiTGlkZXIgdG8gJG1ham9yaXR5IikKICB9Cn0=