leetcode 697. Degree of an Array数组的度
来源:互联网 发布:知乎成都 编辑:程序博客网 时间:2024/06/05 03:41
问题描述:
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.
Note:
- nums.length will be between 1 and 50,000.
- nums[i] will be an integer between 0 and 49,999.
思路:
首先要求出这个数组的度,需要遍历整个数组,将元素的值和对应出现的次数以键值对的形式放入map中存储,同时还要记录每个元素第一次出现的索引值和最后一次出现的索引值,最后得到同一元素出现的最多次数。然后比较每个出现最多次数的元素的首尾差值长度,求最小值。
代码:
class Solution { public int findShortestSubArray(int[] nums) { if(nums.length == 0) return 0; int max = 1; int min = 50000; HashMap<Integer, Integer> map = new HashMap<>(); HashMap<Integer, Integer> firstPoint = new HashMap<>(); HashMap<Integer, Integer> lastPoint = new HashMap<>(); List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < nums.length; i++){ if(map.containsKey(nums[i])){ map.replace(nums[i], map.get(nums[i])+1); lastPoint.replace(nums[i], i); if(map.get(nums[i]) > max) max = map.get(nums[i]); } else{ map.put(nums[i], 1); firstPoint.put(nums[i], i); lastPoint.put(nums[i], i); } } for(Integer it : map.keySet()){ if(map.get(it).equals(max)) list.add(it); } for(Integer it : list){ int a = lastPoint.get(it) - firstPoint.get(it) + 1; min = a > min ? min : a; } return min; }}
阅读全文
0 0
- leetcode 697. Degree of an Array数组的度
- LeetCode 697. Degree of an Array
- leetcode-697. Degree of an Array
- 【LeetCode】697. Degree of an Array
- LeetCode-697. Degree of an Array
- LeetCode-697:Degree of an Array (度相同的最小子数组)
- leetCode-Degree of an Array
- 697. Degree of an Array
- 697. Degree of an Array
- 697. Degree of an Array
- 697. Degree of an Array
- 697. Degree of an Array
- LeetCode.697 Degree of an Array
- leetcode 697[easy]---Degree of an Array
- LWC 54:697. Degree of an Array
- 697 Degree of an Array
- Degree of an Array问题及解法
- LeetCode697. Degree of an Array解答
- Python中文编码问题
- 关于正点原子探索者的介绍
- exit()和_exit()的区别
- 建立软链接
- 架构设计
- leetcode 697. Degree of an Array数组的度
- 在python中,用scatter绘制散点图,自动读取数据
- Java程序员必读之热门书单
- yuv,pcm合成mp4
- 关于计算订单价格,转换后差一分钱的解决方法(浮点数精度问题)
- 狗屎一样的React(第三节,创建app顶部标题栏)
- EasyUI Datagrid 客户端分页详解
- mfc 中child属性的两个窗口重叠 解决重叠部分不停闪烁问题
- java(6)面向对象(第二天)