Easy 169题 Majority Element
来源:互联网 发布:常用排序算法 编辑:程序博客网 时间:2024/05/06 21:28
Question:
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:
sort is always a good idea for may array problem , but we prefer to use hashmap here and we should pay attention to the difference between Integer and int
public class Solution { public int majorityElement(int[] nums) { /*This is amazing.......*/ /* Arrays.sort(nums); return nums[nums.length / 2]; */ /*Hash*/ HashMap<Integer, Integer> res = new HashMap<>(); int ans=0; int n=nums.length; int i=0; Iterator iter = res.entrySet().iterator(); for(i=0;i<=n-1;i++) { if(!res.containsKey(nums[i])) res.put(nums[i],1); else { int tmp=res.get(nums[i]).intValue()+1; res.put(nums[i],tmp); } } iter = res.entrySet().iterator(); while(iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if((int)(entry.getValue())>Math.floor(n/2)) ans=(int)(entry.getKey()); } return ans; }}
0 0
- Easy 169题 Majority Element
- [Leetcode 169, Easy] Majority Element
- <LeetCode><Easy> 169 Majority Element
- 【Leetcode-Easy-169】 Majority Element
- Majority Element (easy)
- 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)
- leetcode 169 Majority Element(难易度:Easy)
- Easy-题目11:169. Majority Element
- Leetcode 169. Majority Element (Easy) (cpp)
- 169. Majority Element 难度:Easy 类别:分治
- Majority Element——Difficulty:Easy
- LeetCode解题报告 169. Majority Element [easy]
- win7 安装sql server 2008 r2
- [leetcode] 407. Trapping Rain Water II 解题报告
- theano
- svn中$Id$无法展开的对应方法
- Trouble-Shooting:remote_listener重新设定
- Easy 169题 Majority Element
- 微服务产品级敏捷设计的初衷
- Trouble-Shooting: HPUX上FTP无法连接
- 微信小程序要这样去解读
- HPUX上的MQ安装
- Android MVP 模式应用实例
- 【tyvj】1030 乳草的入侵 bfs
- LUCENE中的文件操作都是通过这Directory来实现的
- 生成树字符串