集合框架的使用---Majority Number II
2016-01-27 14:06
344 查看
Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.
Find it.
Have you met this question in a real interview? Yes
Example
Given [1, 2, 1, 2, 1, 3, 3], return 1.
Note
There is only one majority number in the array.
Challenge
O(n) time and O(1) extra space.
Find it.
Have you met this question in a real interview? Yes
Example
Given [1, 2, 1, 2, 1, 3, 3], return 1.
Note
There is only one majority number in the array.
Challenge
O(n) time and O(1) extra space.
public class Solution { /** * @param nums: a list of integers * @return: find a majority number */ public int majorityNumber(ArrayList<Integer> nums) { // write your code int n = nums.size(); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int elem : nums) { if (map.containsKey(elem)) { map.put(elem, map.get(elem)+1); }//添加元素.........取值 else { map.put(elem, 1);//添加元素 } } for (int item : map.keySet()) { if (map.get(item) > n/3) { return item;//遍历 } } return -1; } }
相关文章推荐
- java poi excel
- usb之CI13XXX_CONTROLLER_SUSPEND_EVENT
- 愿意花多大的代价?
- 2016年01月
- 微信公众平台--2.获取接口调用凭据
- 语言的静态分析技术
- input type="submit" 和"button"有什么区别?
- SugarCRM源码分析之ViewFactory
- opencart mail服务器的配置
- ServerStatus 输出说明
- swift中单例的实现方法
- Ubuntu 14.04 64位使用Google字体(英文、中文分别修改)
- C++类中成员变量和成员指针变量小结
- python的thread使用
- Spring RMI调用远程方法
- 算法题2 动态规划之最大子序列和&最大子矩阵和
- HDU 1033 Edge
- MSSQL STUFF
- 广州易幻网络科技有限公司Android笔面经 (未通过)
- 配置xheditor图片上传功能