Sunday, September 17, 2017

414. Third Maximum Number


default minHeap

If we need a maxHeap, we can write
PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
Version #1 Priority Queue
18.80 %
class Solution {
    public int thirdMax(int[] nums) {
        if (nums == null || nums.length == 0) throw new IllegalArgumentException();
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        Set<Integer> visited = new HashSet<>();
        int max = nums[0];
        for (int num : nums) {
            if (visited.contains(num)) continue;
            max = Math.max(num, max);
            if (minHeap.size() < 3) {
                minHeap.offer(num);
            } else {
                if (num >= minHeap.peek()) {
                    minHeap.poll();
                    minHeap.offer(num);
                }
            }
            visited.add(num);
        }
        return minHeap.size() == 3 ? minHeap.peek() : max;
    }
}

Version #2 Direct Compare
以为很简单,其实爆炸难写
难点主要是duplicate和不够3个distinct Integers的处理

一开始我把三个值都设成num[0], 发现错的离谱,比如[3, 2, 1] 如果一开始都是3的话,后面就没法Update了
所以一开始都设成null
然后又有问题,譬如second是null,不能无脑把second设成当前值,因为有可能当前的值等于first,就会有duplicate
这里面具体的逻辑还是没搞清,看到答案写先和三个值比一下,如果相等就continue,觉得很有道理
但是自己写的时候 nums[i] == first 这种写法是会报NulPointerException的
所以应该写成!! Integer n : nums ....    n.equals(first)
可以说非常考基本功了
33.14 %

class Solution {
    public int thirdMax(int[] nums) {
        if (nums == null || nums.length == 0) throw new IllegalArgumentException();
        Integer first = null;
        Integer second = null;
        Integer third = null;
        //case1     case2    case3     case4
        //       1        2        3
        for (Integer n : nums) {
            // if nums[i] == 1st/2nd/3rd, we do nothing
            if (n.equals(first) || n.equals(second) || n.equals(third)) continue;
            if (first == null || n > first) {
                third = second;
                second = first;
                first = n;
            } else if (second == null || n > second) {
                third = second;
                second = n;
            } else if (third == null || n > third) {
                third = n;
            }
        }
        return third == null ? first : third;
    }
}

No comments:

Post a Comment