LeetCode 1429: First Unique Number
Problem Description
Explanation:
To solve this problem, we can use a combination of a queue and a hashmap. The queue will store the order of appearance of each unique number, while the hashmap will store the frequency of each number.
- Initialize a queue and a hashmap.
- Iterate over the given array:
- If the number is not in the hashmap, add it to the queue and set its frequency to 1 in the hashmap.
- If the number is already in the hashmap, increment its frequency.
- While the queue is not empty and the front element's frequency is more than 1, remove it from the queue.
- If the queue is not empty, return the front element as the first unique number. Otherwise, return -1.
Time complexity: O(n) where n is the number of elements in the array. Space complexity: O(n) for the hashmap and the queue.
:
Solutions
import java.util.*;
class FirstUnique {
Queue<Integer> queue;
Map<Integer, Integer> frequency;
public FirstUnique(int[] nums) {
queue = new LinkedList<>();
frequency = new HashMap<>();
for (int num : nums) {
add(num);
}
}
public int showFirstUnique() {
while (!queue.isEmpty() && frequency.get(queue.peek()) > 1) {
queue.poll();
}
return queue.isEmpty() ? -1 : queue.peek();
}
public void add(int value) {
frequency.put(value, frequency.getOrDefault(value, 0) + 1);
if (frequency.get(value) == 1) {
queue.offer(value);
}
}
}
Loading editor...