First Unique Number
https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/531/week-4/3313/
You have a queue of integers, you need to retrieve the first unique integer in the queue.
Implement the FirstUnique class:
FirstUnique(int[] nums)Initializes the object with the numbers in the queue.int showFirstUnique()returns the value of the first unique integer of the queue, and returns -1 if there is no such integer.void add(int value)insert value to the queue.
Example 1:
Input:
["FirstUnique","showFirstUnique","add","showFirstUnique","add","showFirstUnique","add","showFirstUnique"]
[[[2,3,5]],[],[5],[],[2],[],[3],[]]
Output:
[null,2,null,2,null,3,null,-1]
Explanation:
FirstUnique firstUnique = new FirstUnique([2,3,5]);
firstUnique.showFirstUnique(); // return 2
firstUnique.add(5); // the queue is now [2,3,5,5]
firstUnique.showFirstUnique(); // return 2
firstUnique.add(2); // the queue is now [2,3,5,5,2]
firstUnique.showFirstUnique(); // return 3
firstUnique.add(3); // the queue is now [2,3,5,5,2,3]
firstUnique.showFirstUnique(); // return -1
Example 2:
Example 3:
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^81 <= value <= 10^8At most
50000calls will be made toshowFirstUniqueandadd.
实现一种支持O(1)时间查询最早出现的独特元素的数据结构,能实时插入并且当插入的数据已出现过时,该元素将不再看作独特。O(1)时间查询 => Hash Map,O(1)找最早出现并且能O(1)删除 => Doubly Linked List + Hash Map。可以用Python带的OrderedHashMap实现。为了及时释放已不再是独特的元素node所占的内存,用单独一个hash set记录出现过的数据。
Last updated
Was this helpful?