1 minute read

Given an array of integers nums, return the largest integer that only occurs once. If no integer occurs once, return -1.
Solving this problem actually requires solving two problems. The first problem is finding out which values only occur once. The second problem is finding the maximum value of those values.

URL: https://leetcode.com/problems/largest-unique-number/solution/

My solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public int largestUniqueNumber(int[] nums) {
        //count the occurences
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num,map.getOrDefault(num,0) + 1);
        }
        //return the occurence with the max value
        int max = -1;
        for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                max = Math.max(max, entry.getKey());
            }
        }
        return max;
    }
}

Explanation:
Lines 4-7 is the code that will count the occurences of a value in an array. A HashMap is used for fast lookups, O(1) average, and the array is traversed in linear time.

Lines 9 -14 is the code for tracking the maximum value of those values that occur once. ‘max’ is initialized to -1 and if there are no values with a frequency of 1, then max is returned as -1. An entry set is created from the map and then it is traversed. If the value has a frequency of 1 (entry.getValue() == 1), then it is a candidate for a maximum value.

Line 15 returns the answer.