前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指offer | 面试题31:数组中出现次数超过一半的数字

剑指offer | 面试题31:数组中出现次数超过一半的数字

作者头像
千羽
发布2021-12-29 13:27:05
4150
发布2021-12-29 13:27:05
举报
文章被收录于专栏:程序员千羽

死磕算法系列文章

  1. 干货 | 手撕十大经典排序算法
  2. 剑指offer | 认识面试
  3. 剑指offer | 面试题2:实现Singleton模式
  4. 剑指offer | 面试题3:二维数组的查找
  5. 剑指offer | 面试题4:替换空格
  6. 剑指offer | 面试题5:从尾到头打印链表
  7. 剑指offer | 面试题6:重建二叉树
  8. 剑指offer | 面试题7:用两个栈实现队列
  9. 剑指offer | 面试题8:旋转数组的最小数字
  10. 剑指offer | 面试题9:斐波那契数列
  11. 剑指offer | 面试题10:青蛙跳台阶问题
  12. 剑指offer | 面试题11:矩阵覆盖
  13. 剑指offer | 面试题12:二进制中1的个数
  14. 剑指offer | 面试题13:数值的整数次方
  15. 剑指offer | 面试题14:打印从1到最大的n位数
  16. 剑指offer | 面试题15:删除链表的节点
  17. 剑指offer | 面试题16:将数组中的奇数放在偶数前
  18. 剑指offer | 面试题17:链表中倒数第k个节点
  19. 剑指offer | 面试题18:反转链表
  20. 剑指offer | 面试题19:合并两个有序链表
  21. 剑指offer | 面试题20:判断二叉树A中是否包含子树B
  22. 剑指offer | 面试题21:二叉树的镜像
  23. 剑指offer | 面试题22:顺时针打印矩阵
  24. 剑指offer | 面试题23:包含min函数的栈
  25. 剑指offer | 面试题24:栈的压入、弹出序列
  26. 剑指offer | 面试题25:从上到下打印二叉树
  27. 剑指offer | 面试题26:二叉搜索树的后序遍历序列
  28. 剑指offer | 面试题27:二叉树中和为某一值的路径
  29. 剑指offer | 面试题28:复杂链表的复制
  30. 剑指offer | 面试题29:二叉搜索树转换为双向链表
  31. 剑指offer | 面试题30:字符串的排列

Leetcode : https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/

GitHub : https://github.com/nateshao/leetcode/blob/main/algo-notes/src/main/java/com/nateshao/sword_offer/topic_31_majorityElement/Solution.java

剑指 Offer 39. 数组中出现次数超过一半的数字

题目描述 :数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

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

难度:简单

示例:

代码语言:javascript
复制
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2

解题思路:

“本文将 “数组中出现次数超过一半的数字” 简称为 “众数” 。 需要注意的是,数学中众数的定义为 “数组中出现次数最多的数字” ,与本文定义不同。

本题常见的三种解法:

  1. 哈希表统计法:遍历数组 nums ,用HashMap统计各数字的数量,即可找出众数。此方法时间和空间复杂度均为O(N)。
  2. 数组排序法:将数组nums 排序,数组中点的元素一定为众数。
  3. 摩尔投票法:核心理念为票数正负抵消。此方法时间和空间复杂度分别为O(N)和0(1),为本题的 最佳解法。

摩尔投票法:

“设输入数组 nums 的众数为x,数组长度为n。

推论一: 若记众数的票数为+1,非众数的票数为-1,则一定有所有数字的票数和> 0。推论二: 若数组的前a个数字的票数和=0,则数组剩余(n-a)个数字的票数和一定仍> 0,即后(n- a)个数字的众数仍为x。

根据以上推论,记数组首个元素为n1,众数为x,遍历并统计票数。当发生票数和= 0时,剩余数组的众 数-定不变,这是由于:

  • 当n1=x:抵消的所有数字中,有一半是众数x。
  • 当n1≠x:抵消的所有数字中,众数x的数量最少为0个,最多为一半。

利用此特性,每轮假设发生票数和 = 0 都可以 缩小剩余数组区间 。当遍历完成时,最后一轮假设的数字即为众数。

算法流程:

  1. 初始化: 票数统计 votes = 0 , 众数 x
  2. 循环: 遍历数组 nums 中的每个数字 num
    1. 当 票数 votes 等于 0 ,则假设当前数字 num 是众数;
    2. num = x 时,票数 votes 自增 1 ;当 num != x 时,票数 votes 自减 1 ;
  3. 返回值: 返回 x 即可;

复杂度分析:

  • 时间复杂度 O(N) : N 为数组 nums 长度。
  • 空间复杂度 O(1) : votes 变量使用常数大小的额外空间。
代码语言:javascript
复制
public static int majorityElement1(int[] nums) {
        int x = 0, votes = 0;
        for(int num : nums){
            if(votes == 0) x = num;
            votes += num == x ? 1 : -1;// votes = votes + ( num == x ? 1 : -1);
        }
        return x;
    }

拓展: 由于题目说明 给定的数组总是存在多数元素 ,因此本题不用考虑 数组不存在众数 的情况。若考虑,需要加入一个 “验证环节” ,遍历数组 nums 统计 x 的数量。

  • x 的数量超过数组长度一半,则返回 x
  • 否则,返回未找到众数;

时间和空间复杂度不变,仍为 O(N)和 O(1) 。

代码语言:javascript
复制
public int majorityElement11(int[] nums) {
        int x = 0, votes = 0, count = 0;
        for(int num : nums){
            if(votes == 0) x = num;
            votes += num == x ? 1 : -1;
        }
        // 验证 x 是否为众数
        for(int num : nums)
            if(num == x) count++;
        return count > nums.length / 2 ? x : 0; // 当无众数时返回 0
    }

代码

代码语言:javascript
复制
package com.nateshao.sword_offer.topic_31_majorityElement;

import java.util.Arrays;

/**
 * @date Created by 邵桐杰 on 2021/12/5 17:16
 * @微信公众号 程序员千羽
 * @个人网站 www.nateshao.cn
 * @博客 https://nateshao.gitee.io
 * @GitHub https://github.com/nateshao
 * @Gitee https://gitee.com/nateshao
 * Description: 剑指 Offer 39. 数组中出现次数超过一半的数字
 * 题目描述:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数
 * 字。如果不存在则输出 0。
 */
public class Solution {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 2, 2, 5, 4, 2};
        int i1 = majorityElement1(arr);
        int i2 = majorityElement2(arr);
        int i3 = majorityElement3(arr);
        System.out.println("i = " + i1); // i = 2
        System.out.println("i2 = " + i2);
        System.out.println("i3 = " + i3);

    }
    /******************** 精选 *********************/
    public static int majorityElement1(int[] nums) {
        int x = 0, votes = 0;
        for(int num : nums){
            if(votes == 0) x = num;
            votes += num == x ? 1 : -1;// votes = votes + ( num == x ? 1 : -1);
        }
        return x;
    }
    /**************** 拓展 *********************/
    public int majorityElement11(int[] nums) {
        int x = 0, votes = 0, count = 0;
        for(int num : nums){
            if(votes == 0) x = num;
            votes += num == x ? 1 : -1;
        }
        // 验证 x 是否为众数
        for(int num : nums)
            if(num == x) count++;
        return count > nums.length / 2 ? x : 0; // 当无众数时返回 0
    }
    /****************** 剑指offer **********************/
    /**
     * 思路:将首次出现的数 count+1,与之后的数进行比较,相等则+1,否则—1,
     * 最后进行校验是否超过长度的一半。
     *
     * @param nums
     * @return
     */
    public static int majorityElement2(int[] nums) {
        int count = 0;
        int candidate = 0;
        for (int num : nums) {
            if (count == 0) candidate = num;
            count += (num == candidate) ? 1 : -1;
        }
        return checkMoreThanHalf(nums, candidate) ? candidate : 0;
    }

    private static boolean checkMoreThanHalf(int[] array, int number) {
        int times = 0;
        for (int i : array) {
            if (i == number) times++;
        }
        return times * 2 >= array.length;
    }


    public static int majorityElement3(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}

参考文献:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/solution/mian-shi-ti-38-zi-fu-chuan-de-pai-lie-hui-su-fa-by/

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-12-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 千羽的编程时光 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 剑指 Offer 39. 数组中出现次数超过一半的数字
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档