EASY题

697. Degree of an Array

2017-10-15  本文已影响42人  DrunkPian0

https://leetcode.com/contest/leetcode-weekly-contest-54/problems/degree-of-an-array/

Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

感觉可以用dp实现one pass的。
我的代码,理论上O(n),但不是one pass,又丑又长:

    public int findShortestSubArray(int[] nums) {
        if (nums == null) return 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        int maxCount = Collections.max(map.values());
        List<Integer> keyList = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == maxCount) {
                keyList.add(entry.getKey());
            }
        }
        int res = nums.length;
        for (int i = 0; i < keyList.size(); i++) {
            res = Math.min(res, findLength(keyList.get(i), nums));
        }
        return res;
    }

    private int findLength(int key, int[] nums) {
        int start = 0, end = nums.length - 1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == key) {
                start = i;
                break;
            }
        }
        for (int j = nums.length - 1; j > start; j--) {
            if (nums[j] == key) {
                end = j;
                break;
            }
        }
        return end - start + 1;
    }
上一篇下一篇

猜你喜欢

热点阅读