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.

给一个非空非负整数的数组,找出和整个数组最大度相同的最短的子数组。度是一个数组里数字出现频率的最大值。

解法:首先要知道整个数组的度,可用哈希表进行统计。度最大的子数组里,首尾数字都是这个度的数字时,子数组是最短的,在用一个哈希表保存,某一个数字第一次出现的index和最后一次出现的index。还要注意度相同的数字可能不只一个所以要求这几个数字中最短的。

Java:

public static class Solution2 {
public int findShortestSubArray(int[] nums) {
Map<Integer, Integer> count = new HashMap<>();
Map<Integer, Integer> left = new HashMap<>();
Map<Integer, Integer> right = new HashMap<>(); for (int i = 0; i < nums.length; i++) {
count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
if (!left.containsKey(nums[i])) {
left.put(nums[i], i);
}
right.put(nums[i], i);
} int result = nums.length;
int degree = Collections.max(count.values());
for (int num : count.keySet()) {
if (count.get(num) == degree) {
result = Math.min(result, right.get(num) - left.get(num) + 1);
}
}
return result;
}
}

Java:

public int findShortestSubArray(int[] nums) {
if (nums.length == 0 || nums == null) return 0;
Map<Integer, int[]> map = new HashMap<>();
for (int i = 0; i < nums.length; i++){
if (!map.containsKey(nums[i])){
map.put(nums[i], new int[]{1, i, i}); // the first element in array is degree, second is first index of this key, third is last index of this key
} else {
int[] temp = map.get(nums[i]);
temp[0]++;
temp[2] = i;
}
}
int degree = Integer.MIN_VALUE, res = Integer.MAX_VALUE;
for (int[] value : map.values()){
if (value[0] > degree){
degree = value[0];
res = value[2] - value[1] + 1;
} else if (value[0] == degree){
res = Math.min( value[2] - value[1] + 1, res);
}
}
return res;
}  

Python:

class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
counts = collections.Counter(nums)
left, right = {}, {}
for i, num in enumerate(nums):
left.setdefault(num, i)
right[num] = i
degree = max(counts.values())
return min(right[num]-left[num]+1 \
for num in counts.keys() \
if counts[num] == degree)

Python: wo

class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return len(nums) degree = collections.Counter()
index = collections.defaultdict(list)
max_degree = 0
max_num = []
for k, v in enumerate(nums):
degree[v] += 1
if degree[v] > max_degree:
max_degree = degree[v]
max_num = []
max_num.append(v)
elif degree[v] == max_degree:
max_num.append(v)
index[v].append(k) min_dis = float('inf')
for v in max_num:
i, j = index[v][0], index[v][-1]
min_dis = min(min_dis, j - i + 1) return min_dis

C++:

class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
int n = nums.size(), res = INT_MAX, degree = 0;
unordered_map<int, int> m;
unordered_map<int, pair<int, int>> pos;
for (int i = 0; i < nums.size(); ++i) {
if (++m[nums[i]] == 1) {
pos[nums[i]] = {i, i};
} else {
pos[nums[i]].second = i;
}
degree = max(degree, m[nums[i]]);
}
for (auto a : m) {
if (degree == a.second) {
res = min(res, pos[a.first].second - pos[a.first].first + 1);
}
}
return res;
}
};

C++:

class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
int n = nums.size(), res = INT_MAX, degree = 0;
unordered_map<int, int> m, startIdx;
for (int i = 0; i < n; ++i) {
++m[nums[i]];
if (!startIdx.count(nums[i])) startIdx[nums[i]] = i;
if (m[nums[i]] == degree) {
res = min(res, i - startIdx[nums[i]] + 1);
} else if (m[nums[i]] > degree) {
res = i - startIdx[nums[i]] + 1;
degree = m[nums[i]];
}
}
return res;
}
};

  

  

All LeetCode Questions List 题目汇总

[LeetCode] 697. Degree of an Array 数组的度的更多相关文章

  1. LeetCode 697. Degree of an Array (数组的度)

    Given a non-empty array of non-negative integers nums, the degree of this array is defined as the ma ...

  2. [LeetCode] Degree of an Array 数组的度

    Given a non-empty array of non-negative integers nums, the degree of this array is defined as the ma ...

  3. leetcode 697. Degree of an Array

    题目: Given a non-empty array of non-negative integers nums, the degree of this array is defined as th ...

  4. Leetcode697.Degree of an Array数组的度

    给定一个非空且只包含非负数的整数数组 nums, 数组的度的定义是指数组里任一元素出现频数的最大值. 你的任务是找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度. 示例 1: 输入: [ ...

  5. 【LeetCode】697. Degree of an Array 解题报告

    [LeetCode]697. Degree of an Array 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/degree- ...

  6. 697. Degree of an Array - LeetCode

    697. Degree of an Array - LeetCode Question 697. Degree of an Array - LeetCode Solution 理解两个概念: 数组的度 ...

  7. 【Leetcode_easy】697. Degree of an Array

    problem 697. Degree of an Array 题意:首先是原数组的度,其次是和原数组具有相同的度的最短子数组.那么最短子数组就相当于子数组的首末数字都是统计度的数字. solutio ...

  8. 【LeetCode】697. Degree of an Array 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 求出最短相同子数组度的长度 使用堆求最大次数和最小长 ...

  9. 697. Degree of an Array 频率最高元素的最小覆盖子数组

    [抄题]: Given a non-empty array of non-negative integers nums, the degree of this array is defined as ...

随机推荐

  1. springmvc后台获取表单提交的数据——@ModelAttribute等方式

    1.通过注解ModelAttribute直接映射表单中的参数到POJO.在from中的action写提交的路径,在input的name写参数的名称. package com.demo.model; p ...

  2. POI导出Excel不弹出保存提示_通过ajax异步请求(post)到后台通过POI导出Excel

    实现导出excel的思路是:前端通过ajax的post请求,到后台处理数据,然后把流文件响应到客户端,供客户端下载 文件下载方法如下: public static boolean downloadLo ...

  3. Web前端开发——概述

    前端技术构成: 结构:html,从语义的角度,描述页面结构 样式:css,从审美的角度,美化界面样式 行为:JavaScript,从交互的角度,提升用户体验 前端技术标准: 前端技术的标准就是由W3C ...

  4. java8 Date Localdatetime instant 相互转化(转) 及当天的最大/最小时间

    Java 8中 java.util.Date 类新增了两个方法,分别是from(Instant instant)和toInstant()方法 // Obtains an instance of Dat ...

  5. [Spring boot] CommandLineRunner and Autowired

    Previously we use Application Context to get Bean and Dependenies injection. It is actually easier t ...

  6. 题解 [SCOI2007]修车

    题面 解析 这题要拆点.. 首先,证明一个式子: 设修理员M修了N辆车, 且修每辆车的时间为W1,W2....WN. 那么,这个修理员一共花的时间就为:W1*N+W2*(N-1)+...+WN*1. ...

  7. python在window下环境搭建

    1.Python安装包下载 地址:https://www.python.org/downloads/windows/ 然后找到对应系统版本的安装包 下载完成后,直接运行exe安装.在安装的时候开业勾选 ...

  8. vue 甘特图简单制作

    甘特图(Gantt chart)又称为横道图.条状图(Bar chart).其通过条状图来显示项目,进度,和其他时间相关的系统进展的内在关系随着时间进展的情况.以提出者亨利·L·甘特(Henrry L ...

  9. jQuery属性操作之类样式操作

    类样式的操作:指对DOM属性className进行添加.移除操作.比如addClass().removeClass().toggleClass(). 1. addClass() 1.1 概述 $(se ...

  10. 也谈Tcp/Ip协议

    一. 计算机网络体系结构分层 一图看完本文 计算机网络体系结构分层 计算机网络体系结构分层 不难看出,TCP/IP 与 OSI 在分层模块上稍有区别.OSI 参考模型注重“通信协议必要的功能是什么”, ...