LeetCode_數組的度_Array_E

697. 數組的度

class Solution {
    public int findShortestSubArray(int[] nums) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        Map<Integer, Node> map = new HashMap<>();
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            Node n = map.get(nums[i]);
            if (n == null) {
                n = new Node(1, i, i);
            } else {
                n.times += 1;
                n.end = i;
            }
            max = Math.max(max, n.times);
            map.put(nums[i], n);
        }
        int minLength = nums.length;
        for (int i : map.keySet()) {
            Node n = map.get(i);
            if (n.times == max) {
                minLength = Math.min(minLength, n.end - n.start + 1);
            }
        }
        return minLength;
    }

    class Node {
        int times;
        int start;
        int end;
        Node(int times, int start, int end) {
            this.times = times;
            this.start = start;
            this.end = end;
        }
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章