【Array-easy】697. Degree of an Array 阿里

1. 题目原址

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

2. 题目描述

在这里插入图片描述

3. 题目大意

给定一个数组,degree为一个数组中的元素出现频率最大值。要求寻找这个数组中出现频率最大的元素的最小距离。

4. 解题思路

  • 定义两个数组,一个数组degree存储的是这个元素出现的频率, 另一个数组 head存储的是元素对应的最近的下标位置
  • 首先给head数组赋予初值为 -1
  • 循环遍历数组,
    • 如果head对应的元素的下标值为 -1, 说明之前还没有元素。head存储这个元素对应的下标位置,head的下标是每个元素nums[i]
    • 更新degree对应元素的出现频率。

5. AC代码

class Solution {
    public int findShortestSubArray(int[] nums) {
        int[] head = new int[50001];
        int[] degree = new int[50001];

        for(int i = 0; i < 50000; i++)
            head[i] = -1;

        int  min = nums.length, max = 1;
        for(int i = 0; i < nums.length; i++) {
            if(head[nums[i]] == -1)
                head[nums[i]] = i;
            degree[nums[i]] ++;
            if(degree[nums[i]] > max) {
                max = degree[nums[i]];
                min = i - head[nums[i]] + 1;
            } else if(degree[nums[i]] == max && min > i - head[nums[i]] + 1)
                min = i - head[nums[i]] + 1;
        }
        return min;
    }
}

6. 相似题型

【1】 53. Maximum Subarray 题目原址:https://leetcode.com/problems/maximum-subarray/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值