Third Maximum Number 2021-10-06 02:26

Problem Description

public int thirdMax(int[] nums) {
    TreeSet<Integer> treeSet = new TreeSet<>();
    for (int num : nums) {
        treeSet.add(num);
        if (treeSet.size() > 3) {
            treeSet.remove(treeSet.first());
        }
    }
    return treeSet.size() == 3 ? treeSet.first() : treeSet.last();
}
Runtime Memory
14 ms 42 MB

henryxi leetcode list

EOF