Lintcode: Majority Number III
2016-01-05 05:57
381 查看
Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array. Find it. Have you met this question in a real interview? Yes Example Given [3,1,2,3,2,3,3,4,4,4] and k=3, return 3. Note There is only one majority number in the array. Challenge O(n) time and O(k) extra space
这道题跟Lintcode: Majority Number II思路很像,那个找大于1/3的,最多有两个candidate,这个一样,找大于1/k的,最多有k-1个candidate
维护k-1个candidate 在map里面,key为数字值,value为出现次数。先找到这k-1个candidate后,扫描所有元素,如果该元素存在在map里面,update map;如果不存在,1: 如果map里面有值为count= 0,那么删除掉这个元素,加入新元素;2:map里面没有0出现,那么就每个元素的count--
注意:有可能map里有多个元素count都变成了0,只用删掉一个就好了。因为还有0存在,所以下一次再需要添加新元素的时候不会执行所有元素count-1, 而是会用新元素替代那个为0的元素
这道题因为要用map的value寻找key,所以还可以用map.entrySet(), return Map.Entry type, 可以调用getKey() 和 getValue()
public class Solution { /** * @param nums: A list of integers * @param k: As described * @return: The majority number */ public int majorityNumber(ArrayList<Integer> nums, int k) { // write your code if (nums==null || nums.size()==0 || k<=0) return Integer.MIN_VALUE; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int i = 0; for (; i<nums.size(); i++) { int key = nums.get(i); if (map.containsKey(key)) { map.put(key, map.get(key)+1); } else { map.put(key, 1); if (map.size() >= k) break; } } while (i < nums.size()) { int key = nums.get(i); if (map.containsKey(key)) { map.put(key, map.get(key)+1); } else { if (map.values().contains(0)) { //map contains value 0 map.put(key, 1); // add new element to map //delete key that has value 0 int zeroKey = 0; for (int entry : map.keySet()) { if (map.get(entry) == 0) { zeroKey = entry; break; } } map.remove(zeroKey); } else { for (int nonzeroKey : map.keySet()) { map.put(nonzeroKey, map.get(nonzeroKey)-1); } } } i++; } HashMap<Integer, Integer> newmap = new HashMap<Integer, Integer>(); int max = 0; int major = 0; for (int j=0; j<nums.size(); j++) { int cur = nums.get(j); if (!map.containsKey(cur)) continue; if (newmap.containsKey(cur)) { newmap.put(cur, newmap.get(cur)+1); } else { newmap.put(cur, 1); } if (newmap.get(cur) > max) { major = cur; max = newmap.get(cur); } } return major; } }
相关文章推荐
- Unity3D学习笔记01
- 博客访问量超过38万次
- 项目截图
- POJ 3026 Borg Maze
- xampp改到phpmyadmin的root密碼無法登錄
- Qt Installer Framework的学习
- 发布Qt Quick桌面应用程序的方法
- Populating Next Right Pointers in Each Node
- 《深入理解OSGi:Equinox原理、应用与最佳实践》笔记_1_运行最简单的bundlehelloworld
- 《深入理解OSGi:Equinox原理、应用与最佳实践》笔记_1_运行最简单的bundlehelloworld
- 《深入理解OSGi:Equinox原理、应用与最佳实践》笔记_2_建立开发环境
- 《深入理解OSGi:Equinox原理、应用与最佳实践》笔记_2_建立开发环境
- 2. String to Integer(atoi)
- 129_矩阵下三角问题 (2008 round2 A)
- 1.21-SOT三极管PCB封装制作
- 如何制作.a静态库?合成多架构静态库?
- 情感机器人小冰如何成为公众人物?
- 并发 (三):Group Dispatch and DIY Dispatch
- 125_minimum scalar product (2008 round1A A)
- adnroid sdk 无法安装或者更新 镜像