def thirdMax(self, nums):
a = b = c = -float("inf")
for n in nums:
if n in (a, b, c): continue
if n > a: n, a = a, n
if n > b: n, b = b, n
if n > c: n, c = c, n
return a if c == -float("inf") else c

This is essentially creating and maintaining a priority queue by hand. The speed improvement comes from the relief of the initializing and destroying of the PriorityQueue Java object.

We can always make some speed improvement by using more primitive types other than objects when possible.

@StefanPochmann
could you help why my solution exceed the time limited? Thanks

public class Solution {
public int thirdMax(int[] nums) {
TreeSet<Integer> ts = new TreeSet<Integer>();
for(int n : nums) ts.add(n);
if(ts.size()>=3){
for(int i = 0; i<2;) ts.pollLast();
return ts.last();
}else return ts.last();
}
}