Skip to content

Commit 6fa3887

Browse files
committed
update
1 parent 45bee7a commit 6fa3887

File tree

2 files changed

+47
-8
lines changed

2 files changed

+47
-8
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
export {};
2+
function majorityElement(nums: number[]): number[] {
3+
let cand1 = 0,
4+
cand2 = 0,
5+
vote1 = 0,
6+
vote2 = 0;
7+
8+
for (const num of nums) {
9+
if (num === cand1) vote1++;
10+
else if (num === cand2) vote2++;
11+
else if (vote1 === 0) {
12+
cand1 = num;
13+
vote1 = 1;
14+
} else if (vote2 === 0) {
15+
cand2 = num;
16+
vote2 = 1;
17+
} else {
18+
vote1--;
19+
vote2--;
20+
}
21+
}
22+
// now below process pick the 2 majority candidates, let's re counts their vote
23+
vote1 = 0;
24+
vote2 = 0;
25+
for (const num of nums) {
26+
if (cand1 === num) vote1++;
27+
else if (cand2 === num) vote2++;
28+
}
29+
return [
30+
[cand1, vote1],
31+
[cand2, vote2],
32+
]
33+
.filter((entry) => entry[1] > Math.floor(nums.length / 3))
34+
.map((entry) => entry[0]);
35+
}

src/voting-algorithm/majority-element.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ function majorityElement(nums: number[]): number {
22
/**
33
Voting algorithm
44
5-
For initial, we can have assume first candidate (nums[0]) get the votes = 1 (means one vote)
5+
For initial, we can have assume candidate is 0, and vote = 0. (0 is not the input, so it'll be replace)
66
77
Then iteration, if there's another item (!==candidate) we decrease the votes, otherwise increase.
88
@@ -11,14 +11,18 @@ function majorityElement(nums: number[]): number {
1111
This algorithm could be proven that if there's a candidate has the least N/2 vote, it could not be elimate by other candidates.
1212
1313
**/
14-
const N = nums.length;
15-
let candidate = nums[0],
16-
votes = 1;
14+
let candidate = 0,
15+
vote = 0;
1716

18-
for (let i = 1; i < N; i++) {
19-
if (votes === 0) candidate = nums[i];
20-
21-
votes += nums[i] === candidate ? 1 : -1;
17+
for (const num of nums) {
18+
if (num === candidate) {
19+
vote++;
20+
} else if (vote === 0) {
21+
candidate = num;
22+
vote = 1;
23+
} else {
24+
vote--;
25+
}
2226
}
2327

2428
return candidate;

0 commit comments

Comments
 (0)