【发布时间】:2019-02-12 03:51:37
【问题描述】:
解决方案 1:没有哈希图
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[(nums.length/2)];
}
}
解决方案 2:哈希映射
class Solution {
public int majorityElement(int[] nums) {
for(int i:nums){
if(hm.containsKey(i)){
int cnt=hm.get(i);
if(cnt+1>nums.length/2) return i;
hm.replace(i,cnt+1);
}
else{
if(1> nums.length/2) return i;
hm.put(i,1);
}
}
return -1;
}
}
哪种解决方案更快,为什么?每个解决方案的复杂性是多少?
问题:
给定一个大小为 n 的数组,找出多数元素。多数元素是出现超过 ⌊ n/2 ⌋ 次的元素。
你可以假设数组是非空的并且多数元素总是存在于数组中。
【问题讨论】:
-
这个问题
The majority element is the element that appears more than ⌊ n/2 ⌋ times.和解决方案不匹配 -
if(1> nums.length/2) return i;这不对... -
这似乎是一个家庭作业问题 - 您是否在此处阅读了关于提出家庭作业问题的部分:How do I ask and answer homework questions? 考虑到这一点,您尝试了什么或如何尝试回答您的问题解决方案的速度和复杂性?