diff --git "a/_posts/2024-05-13-Boyer\342\200\223Moore-majority-vote-algorithm.md" "b/_posts/2024-05-13-Boyer\342\200\223Moore-majority-vote-algorithm.md" new file mode 100644 index 0000000..acd3b1e --- /dev/null +++ "b/_posts/2024-05-13-Boyer\342\200\223Moore-majority-vote-algorithm.md" @@ -0,0 +1,75 @@ +--- +layout: post +title: Boyer–Moore majority vote algorithm +date: 2024-05-13 13:30:00 +0800 +categories: algorithm +tags: vote +published: true +--- + +* content +{:toc} + +[Boyer–Moore majority vote algorithm](https://www.cs.utexas.edu/users/moore/best-ideas/mjrty/index.html){:target="_blank"} + +## problem + +[Kotlin Heroes: Practice 10 - Problem A](https://codeforces.com/contest/1959/problem/A){:target="_blank"} + +You are given an array π‘Ž consisting of 𝑛(𝑛β‰₯3) positive integers. +It is known that in this array, all the numbers except one are the same +(for example, in the array [4,11,4,4] all numbers except one are equal to 4). + +Print the index of the element that does not equal others. The numbers in the array are numbered from one. + +**Input**
+The first line contains a single integer 𝑑(1≀𝑑≀100). Then 𝑑 test cases follow.
+The first line of each test case contains a single integer 𝑛(3≀𝑛≀100) β€” the length of the array π‘Ž.
+The second line of each test case contains 𝑛 integers π‘Ž1,π‘Ž2,…,π‘Žπ‘›(1β‰€π‘Žπ‘–β‰€100).
+It is guaranteed that all the numbers except one in the π‘Ž array are the same. + +**Output**
+For each test case, output a single integer β€” the index of the element that is not equal to others. + +**Example** +``` +input +4 +4 +11 13 11 11 +5 +1 4 4 4 4 +10 +3 3 3 3 10 3 3 3 3 3 +3 +20 20 10 + +output +2 +1 +5 +3 +``` + +## solution + +```kotlin +fun main() { + repeat(readln().toInt()) { println(solve()) } +} + +fun solve(): Int { + readln() + val array = readln().split(' ').map { it.toInt() }.toIntArray() + val list = mutableListOf() + repeat(3) { + if (list.isEmpty() || list[0] == array[it]) { + list.add(array[it]) + } else { + list.removeAt(0) + } + } + val majority = list[0] + return array.indexOfFirst { it != majority } + 1 +} +```