Skip to content

Commit b10010d

Browse files
Merge pull request ignacio-chiazzo#33 from ignacio-chiazzo/majority_element
Added majority element
2 parents 73c53a8 + be75884 commit b10010d

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

LeetcodeProblems/Majority_Element.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
Majority Element
3+
https://leetcode.com/problems/majority-element/
4+
5+
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
6+
7+
You may assume that the array is non-empty and the majority element always exist in the array.
8+
9+
Example 1:
10+
11+
Input: [3,2,3]
12+
Output: 3
13+
Example 2:
14+
15+
Input: [2,2,1,1,1,2,2]
16+
Output: 2
17+
18+
Note: You should have a better solution than O(N)
19+
*/
20+
21+
/**
22+
* @param {number[]} nums
23+
* @return {number}
24+
*/
25+
var majorityElement = function(nums) {
26+
if(nums.length === 0)
27+
return -1;
28+
29+
var candidate = nums[0];
30+
var proves = 1;
31+
32+
for(var i = 1; i < nums.length; i++) {
33+
if(nums[i] === candidate)
34+
proves++;
35+
else {
36+
proves--;
37+
if(proves === 0) {
38+
candidate = nums[i];
39+
proves = 1;
40+
}
41+
}
42+
}
43+
44+
return candidate;
45+
};
46+
47+
var main = function() {
48+
console.log(majorityElement([2,2,3]));
49+
console.log(majorityElement([2,3,2]));
50+
console.log(majorityElement([1,1,1,2,3,45,1,2,4,1,1]));
51+
}
52+
53+
module.exports.main = main

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,8 @@ Solutions of algorithm problems using Javascript
5656
| [Valid Parentheses ](/LeetcodeProblems/Valid_Parentheses.js) | Easy | https://leetcode.com/problems/valid-parentheses/ |
5757
| [Backspace String Compare ](/LeetcodeProblems/Backspace_String_Compare.js) | Easy | https://leetcode.com/problems/backspace-string-compare/ |
5858
| [Binary Gap ](/LeetcodeProblems/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ |
59-
| [Best Time to Buy and Sell Stock II ](/LeetcodeProblems/Best_Time_To_Buy_And_Sell_Stock_II.js) | Easy | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ |
59+
| [Binary Gap ](/LeetcodeProblems/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ |
60+
| [Majority Element](/LeetcodeProblems/Majority_Element.js) | Easy | https://leetcode.com/problems/majority-element/ |
6061
| [Tic Tac Toe ](/LeetcodeProblems/Tic_Tac_Toe.js) | | |
6162
| [Permutations With Duplicates ](/LeetcodeProblems/Permutations_With_Duplicates.js) | | |
6263
| [Deletion Distance](/LeetcodeProblems/Deletion_Distance.js) | | |

0 commit comments

Comments
 (0)