Created
May 11, 2022 15:40
-
-
Save bhavjot/c00c1b4a48e860bac5570c3c6cf9cafe to your computer and use it in GitHub Desktop.
This file contains 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
public int majorityElement(int[] a, int size) | |
{ | |
//code here | |
var majorElement = -1; | |
var majorElementCount = new Dictionary<int,int>(); | |
for (int i = 0;i<size;i++){ | |
if(majorElementCount.ContainsKey(a[i])){ | |
majorElementCount[a[i]]++; | |
} | |
else{ | |
majorElementCount.Add(a[i],1); | |
} | |
} | |
var maxCount = majorElementCount.Values.Max(); | |
if (maxCount > size/2){ | |
majorElement = majorElementCount.Where (x=>x.Value == maxCount) | |
.Select (x=>x.Key).OrderBy(x=>x).Take(1).FirstOrDefault(); | |
} | |
return majorElement; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment