Problem: Given an array of integers, return the largest integer that only occurs once. If no integer occurs once, return -1.
Example:
Input: [2,5,3,7,4,7,2,3] Output: 5 Explanation: The maximum integer in the array is 7 but it is repeated. The number 5 occurs only once, so it's the answer.
Approach: We can solve it using hashing easily. Just look at the implementation to understand the approach.
Implementation in C#:
public int LargestUniqueNumber(int[] nums)
{
Dictionary<int, int> freqMap = new Dictionary<int, int>();
foreach(int num in nums)
{
if (!freqMap.ContainsKey(num))
{
freqMap[num] = 0;
}
++freqMap[num];
}
int max = int.MinValue;
foreach(var kv in freqMap)
{
if (kv.Value == 1 && kv.Key > max)
{
max = kv.Key;
}
}
return max == int.MinValue ? -1 : max;
}
Complexity: O(n)
No comments:
Post a Comment