题目:

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

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

示例 1:

输入: [3,2,3]
输出: 3
示例 2:

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

分析:

遍历一遍(效率略低)

代码:

	public int majorityElement(int[] nums) {
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		int l = nums.length;
        if(l<3)
            return nums[0];
		for (int i : nums) {
			if (map.containsKey(i)) {
				int num = map.get(i);
				if (num + 1 > l / 2)
					return i;
				map.put(i, num + 1);
			} else {
				map.put(i, 1);
			}
		}
		return 0;
	}

效率:

leetcode:169. 求众数

总结:

效率略低

相关文章:

  • 2021-06-27
  • 2021-08-24
  • 2021-07-23
  • 2022-01-04
  • 2021-11-23
  • 2021-07-30
  • 2022-12-23
  • 2021-08-06
猜你喜欢
  • 2021-12-04
  • 2021-05-18
  • 2021-09-25
  • 2021-08-28
  • 2021-10-16
  • 2022-12-23
相关资源
相似解决方案