Last active
June 25, 2020 08:02
-
-
Save bharathmuppa/d2cdf2465e228dfa2de515d639a493ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Given an array of size n, find the majority element. | |
| The majority element is the element that appears more than floor(n/2) times. | |
| You may assume that the array is non-empty and the majority element always exist in the array. | |
| */ | |
| /* | |
| This solution complexity is | |
| worst case : o(n) | |
| best case: o(n/2) => though it is said as o(n), there is nothing wrong to mention as n/2 in best case | |
| */ | |
| function solution(A) { | |
| let length = A.length; | |
| switch (true) { | |
| case (length <= 1): | |
| return 0; | |
| case (length > 1): | |
| return getMajority(A); | |
| default: | |
| throw "I am weird case"; | |
| break; | |
| } | |
| } | |
| function getMajority(A) { | |
| const obj = {}; | |
| const highest = Math.floor(A.length / 2); | |
| let firstHighest = 0; | |
| let result = 0; | |
| for (let i = 0; i < A.length; i++) { | |
| let e = A[i]; | |
| if (!obj[e]) | |
| obj[e] = 1; | |
| else { | |
| obj[e] += 1; | |
| obj[e] > firstHighest ? (result = e, firstHighest = obj[e]) : firstHighest; | |
| if (firstHighest > Math.floor(A.length / 2)) { | |
| // console.log("I will break here beacuse, no need to procees"); | |
| return result; | |
| } | |
| } | |
| } | |
| return result; | |
| } | |
| //solution([2,2,2,2,3,2,2,4,30,30,30,30,30,40]) => 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment