/**
* Return the dominator of the given array.
*
* The dominator is the value that occurs in more than half of the elements of
* the given array.
*
* @param nums Array of numbers.
*
* @returns `-1` if there is no dominator.
*
* @example
* dominator([3,4,3,2,3,1,3,3]) → 3
* dominator([1,2,3,4,5]) → -1 // No val occurs more than half the array
*/functiondominator(nums:number[]):number{for(constitemofnewSet(nums)){if(nums.filter(i=>i===item).length>nums.length/2){returnitem;}}return-1;}
intdominator(vector<int>arr){// stores the number with its countunordered_map<int,int>numCount;// if count of any number becomes more than arr.size()/2// then return that numberfor(intnum:arr){if(++numCount[num]>arr.size()/2)returnnum;}// if no number has count more than arr.size()/2// then return -1return-1;}
The edge cases made this one tricky. Here's a working function in Ruby without using Tally
defdominator(arr)baseline=arr.length/2# Tally how many times each `n` is in the array# Sort by value# Delete any entries where the value is less than or equal to the baseline (half the length of the array)# Put values in order, largest to smallest# Turn it back into a hashresult=arr.inject(Hash.new(0)){|memo,item|memo[item]+=1;memo}.sort_by{|key,value|value}.delete_if{|key,value|value<=baseline}.reverse.to_hresult!={}?result.values.first:-1end
Not tested (written on the phone) but should do the trick
C#
publicstaticintGetDominator(IEnumerable<int>arr){varnum=arr.Count()/2;returnarr.GroupBy(x=>x).Where(x=>x.Count()>num).OrderByDesc(x=>x.Count())//in case there are more than one.FirstOrDefault()?//pick the one most often or null, if there are none .First()??-1;}
Doing this taught me about Array.prototype.some. I originally wanted to use .forEach, but needed a way to break out of the loop once we found the dominator -- no need to keep processing once the answer has been found, especially if the scenario was an array of something ridiculous, like 15,000 items.
TypeScript
A solution in JavaScript:
Swift solution :
And hardcore version :
Go Soultion
output:
C++ solution
The edge cases made this one tricky. Here's a working function in Ruby without using Tally
Results
Not tested (written on the phone) but should do the trick
C#
Here's my solution in JavaScript. I'm not sure how to embed Gists, but here is the link to it .... 😥
Doing this taught me about Array.prototype.some. I originally wanted to use .forEach, but needed a way to break out of the loop once we found the dominator -- no need to keep processing once the answer has been found, especially if the scenario was an array of something ridiculous, like 15,000 items.
.tallyis the best!Java: