Degree of an Array问题及解法
来源:互联网 发布:java server error 编辑:程序博客网 时间:2024/05/29 14:18
问题描述:
Give a string s
, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
示例:
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.
Input: [1,2,2,3,1,4,2]Output: 6
问题分析:
统计每个元素出现的次数,每个元素开始出现的位置和最后出现的位置,找到出现次数最多的元素的在数组中的最短长度即可。
过程详见代码:
class Solution {public: int findShortestSubArray(vector<int>& nums) { unordered_map<int, pair<int, int>> m1;unordered_map<int, int> m2;int count = 0,res = nums.size();for (int i = 0; i < nums.size(); i++){m2[nums[i]]++;if (m1.find(nums[i]) == m1.end()) m1[nums[i]] = pair<int, int>(i, i);else m1[nums[i]].second = i;if (m2[nums[i]] > count) count = m2[nums[i]];}for (auto num : m2){if (count == num.second){res = min(res, m1[num.first].second - m1[num.first].first + 1);}}return res; }};
阅读全文
0 0
- 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-Degree of an Array
- 697. Degree of an Array
- 697. Degree of an Array
- LWC 54:697. Degree of an Array
- LeetCode697. 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 697[easy]---Degree of an Array
- Shuffle an Array问题及解法
- Maximum XOR of Two Numbers in an Array问题及解法
- Spring Bean
- Python中的装饰器
- 虚拟机ubuntu安装gitlab
- 马化腾:谈谈我创办腾讯这些年
- 逻辑回归原理
- Degree of an Array问题及解法
- 从android-apt切换到annotationProcessor
- HTML表单
- 菜鸟先飞之JAVA_多线程
- network Tools
- linux centos shell脚本自动化部署jdk
- linux进程间通信之信号量
- python经常管理supervisor简单介绍
- 报名 | 东南大学周张泉:基于知识图谱的推理技术