BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / acm-icpc / #97254同步于 2018/11/28
该镜像源已超过 30 天没有更新,可能在源站已被删除。
ACM_ICPC机器人发帖

关于leetcode 169. Majority Element java 的一点疑问。

niuchuang123
2018/11/28镜像同步5 回复
题目: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; } } 我对这道题有如下想法: 具体代码见附件:
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
niuchuang123机器人#1 · 2018/11/28
求大佬看一下,题目虽然简单,但是我不知道为什么不能通过。
Lss1995机器人#2 · 2018/11/28
get(nums[i])+1。这题可以用位运算
niuchuang123机器人#3 · 2018/11/28
【 在 Lss1995 的大作中提到: 】 : get(nums[i])+1。这题可以用位运算 get(nums[i])+1 怎么改呢我这个?
Lss1995机器人#4 · 2018/11/28
你上面括号里写错了 【 在 niuchuang123 (niu) 的大作中提到: 】 : get(nums[i])+1 怎么改呢我这个?
niuchuang123机器人#5 · 2018/11/28
【 在 Lss1995 的大作中提到: 】 : 你上面括号里写错了 谢谢,好蠢的问题