原题链接在这里: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: [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.

题解:

找出最大的frequency, 并标注对应的element出现过的左右index位置.

Time Complexity: O(n). n = nums.length.

Space: O(n).

AC Java:

 class Solution {
public int findShortestSubArray(int[] nums) {
HashMap<Integer, Integer> count = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> leftInd = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> rightInd = new HashMap<Integer, Integer>();
int degree = 0; for(int i = 0; i<nums.length; i++){
count.put(nums[i], count.getOrDefault(nums[i], 0)+1);
degree = Math.max(degree, count.get(nums[i])); if(leftInd.get(nums[i]) == null){
leftInd.put(nums[i], i);
}
rightInd.put(nums[i], i);
} int res = Integer.MAX_VALUE;
for(int i = 0; i<nums.length; i++){
if(count.get(nums[i]) == degree){
res = Math.min(res, rightInd.get(nums[i]) - leftInd.get(nums[i]) + 1);
}
} return res;
}
}

最新文章

  1. 新手学习web遇到的一些乱码问题
  2. C#/VB.NET Excel数据分列
  3. HTTPf服务器(3)
  4. markdown语法说明
  5. DBUtils
  6. 使用ISO文件安装Linux
  7. [asp.net mvc]自定义filter
  8. [转] What is Ec/Io (and Eb/No)?
  9. fstab 介绍
  10. VirtualBox安装linux增强工具报错
  11. 九、cocos2dx之Actions
  12. 使用hadoop命令rcc生成Record 一个简单的方法来实现自己的定义writable对象
  13. 【Codeforces 837D】Round Subset
  14. EffectiveC++笔记 目录
  15. B/S架构
  16. Django积木块五——分页
  17. (转载)intellj idea 如何设置类头注释和方法注释
  18. Neural Networks and Deep Learning 课程笔记(第四周)深层神经网络(Deep Neural Networks)
  19. Python实现进度条功能
  20. ios UrlEncode与UrlDecode

热门文章

  1. Linux 设置中文编码
  2. linux 配置tensorflow 全过程记录
  3. HTML5/CSS3实现图片倒影效果
  4. 【转】React Native中ES5 ES6写法对照
  5. JSP Tomcat8.0运行连接池时发生异常【AbstractMethodError oracle.jdbc.driver.T4CConnection.isValid(I)Z】
  6. React之JSX语法
  7. 【I/O】常见输入输出
  8. [Ctsc2000]冰原探险
  9. Java Swing窗体小工具实例 - 原创
  10. 使用ConcurrentLinkedQueue惨痛的教训