697. Degree of an Array

package LeetCode_697

/**
 * 697. Degree of an Array
 * https://leetcode.com/problems/degree-of-an-array/description/
 * 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: nums = [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.

Example 2:
Input: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation:
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.

Constraints:
1. nums.length will be between 1 and 50,000.
2. nums[i] will be an integer between 0 and 49,999.
 * */
class Solution {
    /*
    * solution: HashMap, Time:O(n), Space:O(n);
    * 1. save each num's index of appear by List,
    * 2. find out most frequency number (degree),
    * 3. find out the smallest length of sub-array that has length as same as degree,
    * */
    fun findShortestSubArray(nums: IntArray): Int? {
        val map = HashMap<Int, ArrayList<Int>>()
        for (i in nums.indices) {
            if (!map.contains(nums[i])) {
                val list = ArrayList<Int>()
                list.add(i)
                map.put(nums[i], list)
            } else {
                map.get(nums[i])!!.add(i)
            }
        }
        var degree = 0
        for (item in map) {
            degree = Math.max(degree, item.value.size)
        }
        var result = Int.MAX_VALUE
        for (item in map) {
            //find out the smallest length of sub-array that has length as same as degree,
            if (item.value.size == degree) {
                //calculate the length by index,
                result = Math.min(result, item.value.get(item.value.lastIndex) - item.value.get(0) + 1)
            }
        }
        return result
    }
}

 

posted @ 2021-01-19 22:21  johnny_zhao  阅读(66)  评论(0编辑  收藏  举报