169. Majority Element (Easy)
来源:互联网 发布:windows nt3.1 编辑:程序博客网 时间:2024/05/19 12:14
Given an array of size n, find the majority element. The majority
element is the element that appears more than ⌊ n/2 ⌋ times.You may assume that the array is non-empty and the majority element
always exist in the array.
Solution:
Java:
public class Solution { public int majorityElement(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { if(map.get(nums[i]) == null) { map.put(nums[i], 1); } else { map.put(nums[i], map.get(nums[i]) + 1); } } int majority = nums.length / 2; for (Integer integer : map.keySet()) { if(map.get(integer) > majority) { return integer.intValue(); } } return -1; }}
思路,用Map保存每个数出现的次数,然后遍历map找出Majority Element。
0 0
- 169. Majority Element (Easy)
- 169. Majority Element Easy
- 169. Majority Element [easy] (Python)
- 【LeetCode】169.Majority Element (Easy)
- Leetcode 169. Majority Element[easy]
- LeetCode 169. Majority Element (Easy)
- LeetCode 169. Majority Element (Easy)
- Easy-题目11:169. Majority Element
- Leetcode 169. Majority Element (Easy) (cpp)
- 169. Majority Element 难度:Easy 类别:分治
- LeetCode解题报告 169. Majority Element [easy]
- [leetcode 169. Majority Element]easy |week4
- Majority Element (easy)
- [Leetcode 169, Easy] Majority Element
- <LeetCode><Easy> 169 Majority Element
- Easy 169题 Majority Element
- 【Leetcode-Easy-169】 Majority Element
- Leet Code OJ 169. Majority Element [Difficulty: Easy]
- 【C++面向对象】函数操作符()的重载
- apt-get build-dep 命令详解
- 高性能场景下,HashMap的优化使用建议
- @RequestBody @ResponseBody
- mac系统环境变量设置
- 169. Majority Element (Easy)
- Spring集合注入的方式(1)
- windows下的session隔离机制以及带来的影响
- android OnGlobalLayoutListener
- python导包路径
- Sublime Text3 配置/插件/技巧(更新中)
- 循环画三角形
- PB如何让数据窗口可以一分为2,中间出现一条分隔线,分隔线右边可以随便拉动,左边固定,方便数据窗口列比较多,且要查看左边的某些数据用.
- eclipse同步视图界面的介绍和冲突解决