leetcode 697[easy]---Degree of an Array
来源:互联网 发布:淘宝情趣用品买家秀 编辑:程序博客网 时间:2024/06/12 08:08
难度:easy
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: 2Explanation: 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
思路: 题目讲得不清不楚,花了些功夫才搞懂。找到所给list里面重复次数最多的那个数的重复次数,即为该list的degree。然后寻找与原list的degree相同的最短子list。也就是重复出现次数最多的那个数在原list中出现的位置的从最左到最右之间的片段。
用enumerate() 遍历list,同时获取索引和对应的值,设计三个dictionary,left 用于存放每个element在list中第一次出现的索引,right用于存放每个element在list中最后出现的索引。count用于存放每个element出现的次数。
最后遍历count,找到所有value=degree的key,取最小值。
阅读全文
0 0
- leetcode 697[easy]---Degree of an Array
- LeetCode.697 Degree of an Array
- leetCode-Degree of an Array
- 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
- 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:Degree of an Array (度相同的最小子数组)
- LWC 54:697. Degree of an Array
- Degree of an Array问题及解法
- LeetCode697. Degree of an Array解答
- python3之1006.换个格式输出整数 (15分)
- 文章标题
- checkTest1
- Kotlin 新手别慌,可先了解这些入门知识
- 排序
- leetcode 697[easy]---Degree of an Array
- Perl中字符串编码的处理
- Cocos2d-x Tutorial 之 Socket的使用(2)
- linux kernel_init
- UVALive 7902
- 最水的一篇博客,仅以此文念今日以自勉
- SkyTabView V0.2.0 更新内容
- iOS 10越狱和Reveal 8分析三方App UI框架教程
- form表单提交的几种方法