Skip to content

Commit 02751ef

Browse files
authored
feat: add javascript solution to lcci problem: No.17.10.Find Majority Element (doocs#371)
* feat: add javascript solution to lcci problem: No.02.01.Remove Duplicate Node * feat: add javascript solution to lcci problem: No.02.02.Kth Node From End of List * feat: add javascript solution to lcci problem: No.02.03.Delete Middle Node * feat: add javascript solution to lcci problem: No.17.04.Missing Number * feat: add javascript solution to lcci problem: No.17.10.Find Majority Element
1 parent 05a4339 commit 02751ef

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

lcci/17.10.Find Majority Element/README.md

+27
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@
3535

3636
<!-- 这里可写通用的实现逻辑 -->
3737

38+
摩尔投票法
39+
3840
<!-- tabs:start -->
3941

4042
### **Python3**
@@ -53,6 +55,31 @@
5355

5456
```
5557

58+
### **JavaScript**
59+
60+
```js
61+
/**
62+
* @param {number[]} nums
63+
* @return {number}
64+
*/
65+
var majorityElement = function(nums) {
66+
let candidate = 0, count = 0;
67+
for (let num of nums) {
68+
if (count == 0) candidate = num;
69+
if (candidate == num) {
70+
count++;
71+
} else {
72+
count--;
73+
}
74+
}
75+
let n = 0;
76+
for (let num of nums) {
77+
if (candidate == num) n++;
78+
}
79+
return n > (nums.length / 2) ? candidate : -1;
80+
};
81+
```
82+
5683
### **...**
5784

5885
```

lcci/17.10.Find Majority Element/README_EN.md

+27
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@
3838

3939
## Solutions
4040

41+
Boyer–Moore majority vote algorithm
42+
4143
<!-- tabs:start -->
4244

4345
### **Python3**
@@ -52,6 +54,31 @@
5254

5355
```
5456

57+
### **JavaScript**
58+
59+
```js
60+
/**
61+
* @param {number[]} nums
62+
* @return {number}
63+
*/
64+
var majorityElement = function(nums) {
65+
let candidate = 0, count = 0;
66+
for (let num of nums) {
67+
if (count == 0) candidate = num;
68+
if (candidate == num) {
69+
count++;
70+
} else {
71+
count--;
72+
}
73+
}
74+
let n = 0;
75+
for (let num of nums) {
76+
if (candidate == num) n++;
77+
}
78+
return n > (nums.length / 2) ? candidate : -1;
79+
};
80+
```
81+
5582
### **...**
5683

5784
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var majorityElement = function(nums) {
6+
let candidate = 0, count = 0;
7+
for (let num of nums) {
8+
if (count == 0) candidate = num;
9+
if (candidate == num) {
10+
count++;
11+
} else {
12+
count--;
13+
}
14+
}
15+
let n = 0;
16+
for (let num of nums) {
17+
if (candidate == num) n++;
18+
}
19+
return n > (nums.length / 2) ? candidate : -1;
20+
};

0 commit comments

Comments
 (0)