class Solution:
def largestUniqueNumber(self, A):
from collections import Counter
count = Counter(A)
max_unique = -1
for num in count:
if count[num] == 1:
max_unique = max(max_unique, num)
return max_unique
class Solution {
public:
int largestUniqueNumber(vector<int>& A) {
unordered_map<int, int> count;
for (int num : A) {
count[num]++;
}
int maxUnique = -1;
for (auto& kv : count) {
if (kv.second == 1) {
maxUnique = max(maxUnique, kv.first);
}
}
return maxUnique;
}
};
class Solution {
public int largestUniqueNumber(int[] A) {
Map<Integer, Integer> count = new HashMap<>();
for (int num : A) {
count.put(num, count.getOrDefault(num, 0) + 1);
}
int maxUnique = -1;
for (int num : count.keySet()) {
if (count.get(num) == 1) {
maxUnique = Math.max(maxUnique, num);
}
}
return maxUnique;
}
}
var largestUniqueNumber = function(A) {
let count = {};
for (let num of A) {
count[num] = (count[num] || 0) + 1;
}
let maxUnique = -1;
for (let num in count) {
if (count[num] === 1) {
maxUnique = Math.max(maxUnique, Number(num));
}
}
return maxUnique;
};
Given an array of integers A
, you are asked to find the largest integer that occurs exactly once in the array. If no such integer exists, return -1
.
A
is an integer. Duplicates may exist.-1
.At first glance, you might consider checking every number in the array and seeing if it is unique (occurs only once), keeping track of the largest such number. However, directly checking each number's occurrence by scanning the whole array each time would be inefficient, especially for large arrays.
To improve, you can count the frequency of each number first, then scan through these counts to find the largest number that appears exactly once. This reduces unnecessary repeated checks and leverages efficient data structures for counting.
The main conceptual shift is from brute-force repeated scanning to a two-pass approach: first count, then select.
To solve this efficiently, follow these steps:
A
.-1
.This method is efficient because it only requires two passes: one to build the count map, and another to determine the answer.
Let's consider the array A = [5, 7, 3, 9, 4, 9, 8, 3, 1]
.
8
The optimized solution is much faster and handles large inputs efficiently.
The key insight is to use a hash map to count occurrences, which allows us to efficiently find the largest number that appears exactly once. This approach is both simple and optimal, running in linear time. By separating the counting and selection steps, we avoid redundant work and make the solution both clear and fast.