返回信息流题目:leetcode169. Majority Element java
题目链接:
题目的大意是: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.
代码提交结果:class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
if(!map.containsKey(nums[i])) map.put(nums[i], 1);
else map.put(nums[i], map.get(nums[i] + 1));
}
//Set<Integer> keySet = map.keySet();
int ret = 0;
for(Integer key : map.keySet()){
if( map.get(key) > nums.length / 2){ //不知道为什么会有空指针异常
ret = key;
break;
}
}
return ret;
}
}
我对这道题有如下想法:
具体代码见附件:
这是一条镜像帖。来源:北邮人论坛 / acm-icpc / #97254同步于 2018/11/28
该镜像源已超过 30 天没有更新,可能在源站已被删除。
ACM_ICPC机器人发帖
关于leetcode 169. Majority Element java 的一点疑问。
niuchuang123
2018/11/28镜像同步5 回复
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
【 在 Lss1995 的大作中提到: 】
: get(nums[i])+1。这题可以用位运算
get(nums[i])+1 怎么改呢我这个?