Largest Unique Number

easy array hash table counting

Problem

You are given an integer array nums. Return the largest integer that appears exactly once in the array. If no integer appears exactly once, return -1.

Inputnums = [5, 7, 3, 9, 4, 9, 8, 3, 1]
Output8
The values appearing exactly once are 5, 7, 4, 8, and 1; the largest of these is 8.

def largest_unique_number(nums):
    count = {}
    for x in nums:
        count[x] = count.get(x, 0) + 1
    ans = -1
    for x, c in count.items():
        if c == 1 and x > ans:
            ans = x
    return ans
function largestUniqueNumber(nums) {
  const count = new Map();
  for (const x of nums) count.set(x, (count.get(x) || 0) + 1);
  let ans = -1;
  for (const [x, c] of count) {
    if (c === 1 && x > ans) ans = x;
  }
  return ans;
}
class Solution {
    public int largestUniqueNumber(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int x : nums) count.put(x, count.getOrDefault(x, 0) + 1);
        int ans = -1;
        for (Map.Entry<Integer, Integer> e : count.entrySet()) {
            if (e.getValue() == 1 && e.getKey() > ans) ans = e.getKey();
        }
        return ans;
    }
}
int largestUniqueNumber(vector<int>& nums) {
    unordered_map<int, int> count;
    for (int x : nums) count[x]++;
    int ans = -1;
    for (auto& e : count) {
        if (e.second == 1 && e.first > ans) ans = e.first;
    }
    return ans;
}
Time: O(n) Space: O(n)