• 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
        }
    }
  • 相关阅读:
    腾讯X5内核使用详解(X5内核播放器使用如何去除控制栏全屏播放)以及一些注意事项
    易语言加壳SDK(宏标记)
    安卓相对布局常用语句
    安卓平分位置layout_weight学习记录
    为什么要前后端分离?各有什么优缺点?
    前端开发技术路线
    超实用的JQuery小技巧
    HTML元素脱离文档流的三种方法
    Promise的理解
    JS闭包是什么?
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14300440.html
Copyright © 2020-2023  润新知