0
点赞
收藏
分享

微信扫一扫

LeetCode Top-100 T169-求众数


题目描述:

给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在众数。

示例 1:

    输入: [3,2,3]

    输出: 3

示例 2:

    输入: [2,2,1,1,1,2,2]

    输出: 2

解题思路:

通过遍历数组nums,将数组元素作为key元素put到hashmap中,最后在对比value值返回key值

代码1

class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> hm = new HashMap<>();
for (int num:nums) {
if (!hm.containsKey(num)) {
hm.put(num,1);
} else {
hm.put(num,hm.get(num)+1);
}
if (hm.get(num) > nums.length/2) {
System.out.println(num);
}
}
}
}

代码2:可以使用sort排序时

class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}

代码3:通过栈实现,不过貌似当nums={2,2,2,1,3,3}时在本地执行不能通过,leetcode上应该是排除这种情况的(数组长度为奇数)

class Solution {
public int majorityElement(int[] nums) {
Stack<Integer> stack = new Stack<>();
for (int i : nums) {
if (stack.empty() || i == stack.peek()) {
stack.push(i);
} else {
stack.pop();
}
}
return stack.peek();
}
}



举报

相关推荐

0 条评论