前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode697. Degree of an Array解答

LeetCode697. Degree of an Array解答

作者头像
vincentbbli
发布2021-08-18 15:35:10
2080
发布2021-08-18 15:35:10
举报
文章被收录于专栏:vincent随笔vincent随笔

一早上起来,先做一道题降降起床气,这道题花了一个小时多十分钟,但是!当我看到accept之后的结果了的时候!

这里写图片描述
这里写图片描述

贼开心

#老规矩,先看一下题目

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.

题目大意是:在一个非空非负的int型数组中,定义degree为一个数组中的元素出现频率最大值。你的任务就是要寻找这个数组中出现频率最大的元素的最小距离(题目有点绕,多读几遍)

Example 1:

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.

Example 2:

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.

解题思路

这个题目一看就不是什么好做的题目,既要频率最大,又要距离最小,这就是在搞事情。 经验告诉我,这种题目要是能只遍历一遍肯定是最好的算法,并且经验还告诉我,如果想要时间复杂度降低,那只有牺牲空间复杂度了,所以我需要额外的空间。 我想的是,维护一个int数组pos来保存它的每个元素在原始数组的位置,全部初始化为0。再维护一个int数组frequency保存它们出现的频率,用一个int变量标记最小长度,初始化为50000。遍历原始数组将每个元素映射到pos数组中,如果不是第一次出现,则计算第一次出现的位置与当前的位置的差,再查看frequency数组的该元素的频率,如果为最高则比较当前距离和全局最小距离取较小值。代码如下:

代码语言:javascript
复制
class Solution {
    public int findShortestSubArray(int[] nums) {
        int minlength=50000;
        int currlength;
        int maxfrequency=0;
        int[] frequency=new int[50001];
        int[] pos=new int[50001];
        
        if(nums.length==1){
            return 1;
        }
        for(int i=1;imaxfrequency){
                    maxfrequency=frequency[nums[i-1]];
                        minlength=currlength;
                }else if(frequency[nums[i-1]]==maxfrequency){
                    minlength=currlength

更好的算法

没有找到效率更高写法更简洁的算法了

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-10-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • #老规矩,先看一下题目
  • 解题思路
  • 更好的算法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档