zoukankan      html  css  js  c++  java
  • 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
        }
    }
  • 相关阅读:
    $().each() 与 $.each()区别,以及 jquery ajax 应用
    sql 随机获取数据
    Content type 'text/plain;charset=UTF-8' not supported
    mvn 安装jar到本地仓库
    idea 插件(字母顺序)
    adb连接逍遥模拟器,并自动设置和清除代理
    git仓库重新创建master分支
    js 日期格式化
    java 去除url中指定参数
    okhttp使用post出现:RFC 7230 and RFC 3986错误
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14300440.html
Copyright © 2011-2022 走看看