Skip to content

Commit 2a00932

Browse files
committed
update the docs for voting algo
1 parent 14b4ad7 commit 2a00932

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

src/voting-algorithm/readme.md

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Summary of Voting-Algo
2+
Boyer-Moore Majority Vote algorithm
23

34
## Prob pattern
45
1. Majority element
@@ -30,4 +31,45 @@ for(const num of nums) {
3031
vote --;
3132
}
3233
}
33-
```
34+
```
35+
36+
## One-third case (majority-element-ii)
37+
Since we wanna find the candidate's `vote > Math.floor(n/3)`, there're **2 potential candidates** could meet it (no possibility for 3 cands, you can rethink about it).
38+
39+
So we keep `cand1/vote1` & `cand2/vote2` and yes! still the same process.
40+
41+
1. Replace the zero vote candidate (replace the candidate now lose authority)
42+
2. Accumulate
43+
```typescript
44+
for (const num of nums) {
45+
// replace
46+
if (vote1 === 0 && num !== cand2) { // ---> yes we need this mutual condition
47+
cand1 = num;
48+
vote1 = 1;
49+
continue;
50+
} else if (vote2 === 0 && num !== cand1) { // --> since we don't want cand1 is same as cand2
51+
cand2 = num;
52+
vote2 = 1;
53+
continue;
54+
}
55+
56+
// accumulate (increment or decrement)
57+
if (cand1 === num) {
58+
vote1++;
59+
} else if (cand2 === num) {
60+
vote2++;
61+
} else {
62+
vote1--;
63+
vote2--;
64+
}
65+
}
66+
```
67+
68+
3. We need to re-analysis the vote of these two candidates, above process is only to pickup the tier two potential candidates (the top 2 highest votes candidate doesn't mean they all `vote > Math.floor(n/3)` ), but we need to know the specific votes.
69+
70+
4. Yes, so now we can filter the potential candidate whiose vote is not greater `Math.floor(n/3)`.
71+
72+
73+
Note:
74+
You might think "Why top 2 highest vote candidates" doesn't meaning all's vote greater than one-third of all.
75+
Counterexample: [1,2,3,3,3] -> you can say top 2 is `[2,3]` (or `[1,3]`) but only the candidate `3` meet the condition.

0 commit comments

Comments
 (0)