From 03aace9fe549c89f1f1043f40456098eeb3499c4 Mon Sep 17 00:00:00 2001 From: Yuchen Pei Date: Mon, 4 Jun 2018 16:48:00 +0200 Subject: added a micropost --- microposts/boyer-moore.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 microposts/boyer-moore.md (limited to 'microposts') diff --git a/microposts/boyer-moore.md b/microposts/boyer-moore.md new file mode 100644 index 0000000..e3e0f9c --- /dev/null +++ b/microposts/boyer-moore.md @@ -0,0 +1,17 @@ +--- +date: 2018-06-04 +--- + +The [Boyer-Moore algorithm for finding the majority of a sequence of elements](https://en.wikipedia.org/wiki/Boyer–Moore_majority_vote_algorithm) falls in the category of "very clever algorithms". + + int majorityElement(vector& xs) { + int count = 0; + int maj = xs[0]; + for (auto x : xs) { + if (x == maj) count++; + else if (count == 0) maj = x; + else count--; + } + return maj; + } + -- cgit v1.2.3