leetcode刷题-169.Majority Element

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.

Example 1:
Input: [3,2,3]
Output: 3

Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2

思路

求众数,而且这个众数出现次数超过一半,所以就用大众化的方法,用map记录每个数字出现的次数,然后找到超过一半的,时间复杂度O(n),空间复杂度O(n)

代码
class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }
        
        for (int key : map.keySet()) {
            if (map.get(key) > nums.length / 2) {
                return key;
            }
        }
        
        return -1;
    }
}

之后看了题解的优质解答,摩尔投票法
基本思想:寻找数组中超过一半的数字,这意味着数组中其他数字出现次数的总和都是比不上这个数字出现的次数
即如果把 该众数记为 +1 ,把其他数记为 −1 ,将它们全部加起来,和是大于 0 的。
所以可以这样操作:

  • 设置两个变量 candidate 和 count,candidate 用来保存数组中遍历到的某个数字,count
    表示当前数字的出现次数,一开始 candidate 保存为数组中的第一个数字,count 为 1
  • 遍历整个数组
  • 如果数字与之前 candidate 保存的数字相同,则 count 加 1
  • 如果数字与之前 candidate 保存的数字不同,则 count 减 1
  • 如果出现次数 count 变为 0 ,candidate 进行变化,保存为当前遍历的那个数字,并且同时把 count 重置为 1
  • 遍历完数组中的所有数字即可得到结果

时间复杂度O(n),空间复杂度O(1)

代码
class Solution {
    public int majorityElement(int[] nums) {
    int candidate = nums[0], count = 1;
    for (int i = 1; i < nums.length; ++i) {
      if (count == 0)  {
        candidate = nums[i];
        count = 1;
      } else if (nums[i] == candidate) {
        count++;
      } else{
        count--;
      }
    }
    return candidate;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值