Leetcode——697. Degree of an Array

40 篇文章 0 订阅
19 篇文章 0 订阅

题目原址

https://leetcode.com/problems/degree-of-an-array/description/

题目描述

Example1:

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.

Example2:

Input: [1,2,2,3,1,4,2]
Output: 6

Note:

  • nums.length will be between 1 and 50,000.
  • nums[i] will be an integer between 0 and 49,999.

解题思路

  • 定义三个HashMap:count –>统计同一数组元素出现的次数;starts –> 统计第一次出现该元素的下标;ends–>统计所有元素最后一次出现的下标
  • 第一次遍历:
    • 第一步:如果在count中不存在该元素,则将它存入count和starts中,否则执行第二步
    • 第二步:将元素存入ends中,将元素值作为键,下标值作为值。
    • 第三步:更改元素的出现次数,按照元素值更改出现的次数。
    • 第四步:修改max,max指现有的元素重复出现的最多的次数
  • 第二次遍历:
    • 使用增强for循环,将count中的所有键取出来,判断键对应的值是否等于max,如果等于max就找到相邻的元素的最小值。

AC代码

class Solution {
    public int findShortestSubArray(int[] nums) {
        int length = nums.length;
        Map<Integer,Integer>  count= new HashMap<Integer,Integer>();
        Map<Integer,Integer> starts = new HashMap<Integer,Integer>();
        Map<Integer,Integer> ends = new HashMap<Integer,Integer>();
        int max = Integer.MIN_VALUE;
        for(int i = 0; i<length; i++) {
            if(!(count.containsKey(nums[i]))) {
                count.put(nums[i], 0);
                starts.put(nums[i], i);
            }
            ends.put(nums[i], i);
            count.put(nums[i], count.get(nums[i])+1);
            max = Math.max(max, count.get(nums[i]));
        }
        int min = Integer.MAX_VALUE;
        for(Integer key:count.keySet()) {
            if(count.get(key) == max) {
                min = Math.min(min, ends.get(key) - starts.get(key) + 1);
            }
        }
        return min;
    }
}

感谢

https://discuss.leetcode.com/topic/107103/java-very-concise-and-easy-solution-beats-100-java-solutions

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值