Java 8 and PriorityQueue


  • 0
    X
    public int thirdMax(int[] nums) {
        final PriorityQueue<Integer> queue = new PriorityQueue<>();
    
        IntStream.of(nums).distinct().forEach(num -> {
            if (queue.size() < 3) {
                queue.add(num);
            } else if (num > queue.peek()) {
                queue.poll();
                queue.add(num);
            }
        });
    
        if (queue.size() < 3) {
            while (queue.size() > 1) {
                queue.poll();
            }
        }
    
        return queue.peek();
    }
    

    Or:

    final long[] a = { Long.MIN_VALUE, Long.MIN_VALUE, Long.MIN_VALUE };
    
    for (int num : nums) {
        for (int i = 0; i < 3; i++) {
            if (num == a[i]) {
                break;
            } else if (num > a[i]) {
                if (i == 0) {
                    a[2] = a[1]; a[1] = a[0];
                } else if (i == 1) {
                    a[2] = a[1];
                }
    
                a[i] = num;            
                break;
            }
        }
    }
    
    return (int) (a[2] == Long.MIN_VALUE || a[1] == Long.MIN_VALUE ? a[0] : a[2]);
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.