Skip to content

feat: add javascript solution to lcci problem: No.17.10.Find Majority Element #371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
May 6, 2021
Merged
27 changes: 27 additions & 0 deletions lcci/17.10.Find Majority Element/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@

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

摩尔投票法

<!-- tabs:start -->

### **Python3**
Expand All @@ -53,6 +55,31 @@

```

### **JavaScript**

```js
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
let candidate = 0, count = 0;
for (let num of nums) {
if (count == 0) candidate = num;
if (candidate == num) {
count++;
} else {
count--;
}
}
let n = 0;
for (let num of nums) {
if (candidate == num) n++;
}
return n > (nums.length / 2) ? candidate : -1;
};
```

### **...**

```
Expand Down
27 changes: 27 additions & 0 deletions lcci/17.10.Find Majority Element/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@

## Solutions

Boyer–Moore majority vote algorithm

<!-- tabs:start -->

### **Python3**
Expand All @@ -52,6 +54,31 @@

```

### **JavaScript**

```js
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
let candidate = 0, count = 0;
for (let num of nums) {
if (count == 0) candidate = num;
if (candidate == num) {
count++;
} else {
count--;
}
}
let n = 0;
for (let num of nums) {
if (candidate == num) n++;
}
return n > (nums.length / 2) ? candidate : -1;
};
```

### **...**

```
Expand Down
20 changes: 20 additions & 0 deletions lcci/17.10.Find Majority Element/Solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
let candidate = 0, count = 0;
for (let num of nums) {
if (count == 0) candidate = num;
if (candidate == num) {
count++;
} else {
count--;
}
}
let n = 0;
for (let num of nums) {
if (candidate == num) n++;
}
return n > (nums.length / 2) ? candidate : -1;
};