diff --git a/LeetcodeProblems/Majority_Element.js b/LeetcodeProblems/Majority_Element.js new file mode 100644 index 0000000..4e4b026 --- /dev/null +++ b/LeetcodeProblems/Majority_Element.js @@ -0,0 +1,53 @@ +/* +Majority Element +https://leetcode.com/problems/majority-element/ + +Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. + +You may assume that the array is non-empty and the majority element always exist in the array. + +Example 1: + +Input: [3,2,3] +Output: 3 +Example 2: + +Input: [2,2,1,1,1,2,2] +Output: 2 + +Note: You should have a better solution than O(N) +*/ + +/** + * @param {number[]} nums + * @return {number} + */ +var majorityElement = function(nums) { + if(nums.length === 0) + return -1; + + var candidate = nums[0]; + var proves = 1; + + for(var i = 1; i < nums.length; i++) { + if(nums[i] === candidate) + proves++; + else { + proves--; + if(proves === 0) { + candidate = nums[i]; + proves = 1; + } + } + } + + return candidate; +}; + +var main = function() { + console.log(majorityElement([2,2,3])); + console.log(majorityElement([2,3,2])); + console.log(majorityElement([1,1,1,2,3,45,1,2,4,1,1])); +} + +module.exports.main = main diff --git a/README.md b/README.md index 96763e3..895cf5d 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,8 @@ Solutions of algorithm problems using Javascript | [Valid Parentheses ](/LeetcodeProblems/Valid_Parentheses.js) | Easy | https://leetcode.com/problems/valid-parentheses/ | | [Backspace String Compare ](/LeetcodeProblems/Backspace_String_Compare.js) | Easy | https://leetcode.com/problems/backspace-string-compare/ | | [Binary Gap ](/LeetcodeProblems/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ | -| [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/ | +| [Binary Gap ](/LeetcodeProblems/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ | +| [Majority Element](/LeetcodeProblems/Majority_Element.js) | Easy | https://leetcode.com/problems/majority-element/ | | [Tic Tac Toe ](/LeetcodeProblems/Tic_Tac_Toe.js) | | | | [Permutations With Duplicates ](/LeetcodeProblems/Permutations_With_Duplicates.js) | | | | [Deletion Distance](/LeetcodeProblems/Deletion_Distance.js) | | |