Skip to content

Commit a984838

Browse files
authored
Update 169-majority-element.js
1 parent 0885e2d commit a984838

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

169-majority-element.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,22 @@ const majorityElement = function(nums) {
1616
.map(el => +el[0])
1717
.sort((a, b) => b - a)[0];
1818
};
19+
20+
// another
21+
22+
/**
23+
* @param {number[]} nums
24+
* @return {number}
25+
*/
26+
const majorityElement = function(nums) {
27+
let cnt = 1, candidate = nums[0]
28+
for(let i = 1, n = nums.length; i < n; i++) {
29+
if(candidate === nums[i]) cnt++
30+
else cnt--
31+
if(cnt === 0) {
32+
cnt = 1
33+
candidate = nums[i]
34+
}
35+
}
36+
return candidate
37+
};

0 commit comments

Comments
 (0)