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: [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

给定非空整数nums的非空数组,该数组的度数被定义为其任何一个元素的最大频率。

你的任务是找到num的(连续的)子阵列的最小可能长度,其与nums具有相同的度数。

例1:
输入:[1,2,2,3,1]
输出:2
说明:
输入数组的度数为2,因为元素1和2都出现两次。
在具有相同程度的子阵列中:
[1,2,2,3,1],[1,2,2,3],[2,2,3,1],[1,2,2],[2,2,3],[2] ,2]
最短的长度是2.所以返回2。
例2:
输入:[1,2,2,3,1,4,2]
输出:6

class Solution {
public int findShortestSubArray(int[] nums) {
int maxcount = 1;
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i : nums) {
if (hm.containsKey(i)) {
hm.put(i, hm.get(i) + 1);
if (maxcount < hm.get(i)) {
maxcount = hm.get(i);
}
} else {
hm.put(i, 1);
}
}
Set<Integer> set = hm.keySet();
int minlength = Integer.MAX_VALUE;
for (int s : set) {
int temp = Integer.MAX_VALUE;
if (hm.get(s) == maxcount) {
int i = 0, j = nums.length - 1;
while (nums[i] != s && i < j)
i++;
while (nums[j] != s && i < j)
j--;
temp = j - i + 1;
}
minlength = Math.min(temp, minlength);
}
return minlength;
}
}

  

最新文章

  1. EFCore执行Sql语句的方法:FromSql与ExecuteSqlCommand
  2. 火狐浏览器+Firebug+FirePath测试Xpath
  3. Eclipse汉化后怎么改回英文版(可切换中英文)
  4. RabbitMQ 用户角色详解
  5. [PL/SQL工具]绿色版PLSQL工具登录时提示初始化失败,无法锁定OCI.dll错误
  6. kvm NET 和 BRIDGE
  7. Hadoop分布式文件系统:架构和设计要点
  8. 教你如何利用xml格式的sitemap文件做好SEO
  9. springMvc(三)session、HandlerInterceptorAdapter
  10. Use XSLT in wix
  11. 每天一条Linux命令(OS X系统上操作)
  12. js window.open()弹出窗口参数说明及居中设置
  13. 分享一个自用的 Inno Setup 软件打包脚本
  14. 动画api说明
  15. 第六节,初识python和字符编码
  16. offsetXXX和scollXXX的一些操作
  17. linq中怎么实现多条件关联的左右连接
  18. leetcode — same-tree
  19. charles如何设置弱网
  20. 自学Zabbix3.5.1-监控项item-key介绍

热门文章

  1. 题解 【Codeforces988E】Divisibility by 25
  2. JQuery-Snowfall降雪插件使用
  3. 在多租户(容器)数据库中如何创建PDB:方法5 DBCA远程克隆PDB
  4. c数据结构 -- 使用链表实现计数
  5. thinkphp中路由的基本使用
  6. Python - python3.7新增的contextvars vs Thread local(threading.local)
  7. python面试的100题(7)
  8. JDK的卸载和安装
  9. index unique scan 与index range scan等的区别
  10. 利用数据结构排序的priority_queue