其他分享
首页 > 其他分享> > 1429. First Unique Number 返回第一个独特的数字

1429. First Unique Number 返回第一个独特的数字

作者:互联网

You have a queue of integers, you need to retrieve the first unique integer in the queue.

Implement the FirstUnique class:

 

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:

Input: 
["FirstUnique","showFirstUnique","add","add","add","add","add","showFirstUnique"]
[[[7,7,7,7,7,7]],[],[7],[3],[3],[7],[17],[]]
Output: 
[null,-1,null,null,null,null,null,17]
Explanation: 
FirstUnique firstUnique = new FirstUnique([7,7,7,7,7,7]);
firstUnique.showFirstUnique(); // return -1
firstUnique.add(7);            // the queue is now [7,7,7,7,7,7,7]
firstUnique.add(3);            // the queue is now [7,7,7,7,7,7,7,3]
firstUnique.add(3);            // the queue is now [7,7,7,7,7,7,7,3,3]
firstUnique.add(7);            // the queue is now [7,7,7,7,7,7,7,3,3,7]
firstUnique.add(17);           // the queue is now [7,7,7,7,7,7,7,3,3,7,17]
firstUnique.showFirstUnique(); // return 17

Example 3:

Input: 
["FirstUnique","showFirstUnique","add","showFirstUnique"]
[[[809]],[],[809],[]]
Output: 
[null,809,null,-1]
Explanation: 
FirstUnique firstUnique = new FirstUnique([809]);
firstUnique.showFirstUnique(); // return 809
firstUnique.add(809);          // the queue is now [809,809]
firstUnique.showFirstUnique(); // return -1

基础知识没学好,不解释。已经补上了

https://leetcode.com/problems/first-unique-number/discuss/601107/JavaPython-3-DoublyLinkedList-and-LinkedHashSetdict-O(n)-2-neat-codes-w-analysis.

private Set<Integer> unique = new LinkedHashSet<>(); 
    private Set<Integer> total = new HashSet<>();
    
    public FirstUnique(int[] nums) {
        for (int n : nums) {
            add(n);
        }
    }
    
    public int showFirstUnique() {
        /*
        for (int v : unique) {
            return v;
        }
        return -1;
        */
        return unique.isEmpty() ? -1 : unique.iterator().next(); // credit to @yelhsabananah
    }
    
    public void add(int value) {
        if (total.add(value)) {
            unique.add(value);
        }else {
            unique.remove(value);
        }
    }

 

标签:null,1429,Number,queue,FirstUnique,add,showFirstUnique,firstUnique,Unique
来源: https://www.cnblogs.com/immiao0319/p/15201818.html