diff --git a/Data-Structures/Array/Find-Majority-Element(Moore's-Voting-Algorithm) b/Data-Structures/Array/Find-Majority-Element(Moore's-Voting-Algorithm) new file mode 100644 index 0000000000..b2758a3284 --- /dev/null +++ b/Data-Structures/Array/Find-Majority-Element(Moore's-Voting-Algorithm) @@ -0,0 +1,46 @@ +/* + +Find all elements in a given integer array that appear more than ⌊ n/3 ⌋ times, n being the size of array. + +Input :- [2,5,3,2,4,2,2] +Output :- 2 + +*/ + +let majorityElement = function(arr) { + + // EDGE CASE + if (arr.length < 3) { + return [...new Set(arr)]; + } + + let temp1 = null, cnt1 = 0; + let temp2 = null, cnt2 = 0; + + for (let x of arr) { + if (x === temp1) { + cnt1 += 1; + } else if (x === temp2) { + cnt2 += 1; + } else if (cnt1 === 0) { + temp1 = x; + cnt1 = 1; + } else if (cnt2 === 0) { + temp2= x; + cnt2= 1; + } else { + cnt1 -= 1; + cnt2 -= 1; + } + } + + let ans = []; + for (let temp of [temp1, temp2]) { + if (arr.filter(num => num === temp).length> Math.floor(arr.length / 3)) { + ans.push(temp); + } + } + return ans; +}; + +console.log(majorityElement([2,5,3,2,4,2,2]));

AltStyle によって変換されたページ (->オリジナル) /