Skip to content

Instantly share code, notes, and snippets.

@bhavjot
Created May 11, 2022 15:40
Show Gist options
  • Save bhavjot/c00c1b4a48e860bac5570c3c6cf9cafe to your computer and use it in GitHub Desktop.
Save bhavjot/c00c1b4a48e860bac5570c3c6cf9cafe to your computer and use it in GitHub Desktop.
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