Leetcode Problem -- 697
来源:互联网 发布:被淘宝网店诈骗 编辑:程序博客网 时间:2024/06/06 02:00
问题理解
一个序列中,有些数字会重复出现多次,如果数n重复出现次数最多,那么寻找一个包含所有n的最短子列。
思路
- 用HashMap存每个数及它出现的次数
- 对Value排序找到最大出现次数的数(集)
- 遍历出现次数最多的数集,同时确定其在序列中首次出现的位置pos1,末次出现位置pos2,找到最小的pos2-pos1+1就是问题的答案
分析
- 时间复杂度O(n)
- 空间复杂度O(n)
- 待优化,但是AC了就懒得弄了
// 有效片段 HashMap<Integer, Integer> hashSet = new HashMap<Integer, Integer>(); for(int num:nums) { if(hashSet.containsKey(num)) { int newVal = hashSet.get(num) + 1; hashSet.put(num, newVal); } else { hashSet.put(num, 1); } } ArrayList<Integer> arrayList = new ArrayList<Integer>(); int max = 0; for(int key:hashSet.keySet()) { if (hashSet.get(key) > max) { max = hashSet.get(key); } } for(int key:hashSet.keySet()) { if (hashSet.get(key)== max) { arrayList.add(key); } } int len = 0, min = 0; for(int poss:arrayList) { int pos1 = 0, pos2 = 0; for (int i = 0; i < nums.length; i++) if (nums[i] == poss) { pos1 = i; break; } for (int i = nums.length -1; i > 0; i--) if (nums[i] == poss) { pos2 = i; break; } if(len == 0) { len = pos2 - pos1 + 1; min = len; }else { len = pos2 - pos1 + 1; if(len < min) min = len; } }
阅读全文
0 0
- Leetcode Problem -- 697
- leetcode Subsets II problem
- Leetcode Problem 汇总一
- Leetcode Problem 汇总二
- leetcode - The Skyline Problem
- leetcode hard problem summary
- LeetCode - The Skyline Problem
- leetcode:the skyline problem
- The Skyline Problem -- leetcode
- LeetCode Problem:Two Sum
- LeetCode Problem:Reverse Integer
- [LeetCode Problem]TwoSum
- Leetcode -- The Skyline Problem
- [LeetCode]problem 77. Combinations
- LeetCode Problem 1解析
- LeetCode Problem 2解析
- LeetCode Problem 3解析
- Leetcode Problem -- 26
- Android之View的知识(getWidth() 和getMeasuredWidth区别 如何在oncreate获取宽高)
- Java发展史
- 浅谈Fortran语言
- SpringMVC 拦截器不拦截静态资源的三种处理方式
- 利用反向ssh从外网访问内网主机
- Leetcode Problem -- 697
- MySQL数据库 之 数据库的基本操作
- 最短路径算法实现
- Failed to bind NettyServer on /192.168.49.1:20880, cause: Failed to bind to: /0.0.0.0:20880
- Linux schedule 1、调度的时刻
- Linux schedule 2、调度算法
- Linux schedule 3、负载计算
- 无界面启动虚拟机
- Leetcode Problem -- 26