zoukankan      html  css  js  c++  java
  • 面试题29:数组中出现次数超过一半的数字

    题目描述

    数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。

    题目分析

    剑指Offer(纪念版)P163

    代码实现

    int MoreThanHalfNum_Solution2(int* numbers, int length)
    {
        if(CheckInvalidArray(numbers, length))
            return 0;
     
        int result = numbers[0];
        int times = 1;
        for(int i = 1; i < length; ++i)
        {
            if(times == 0)
            {
                result = numbers[i];
                times = 1;
            }
            else if(numbers[i] == result)
                times++;
            else
                times--;
        }
     
        if(!CheckMoreThanHalf(numbers, length, result))
            result = 0;
     
        return result;
    }
    
    bool g_bInputInvalid = false;
    
    bool CheckInvalidArray(int* numbers, int length)
    {
        g_bInputInvalid = false;
        if(numbers == NULL && length <= 0)
            g_bInputInvalid = true;
    
        return g_bInputInvalid;
    }
    
    bool CheckMoreThanHalf(int* numbers, int length, int number)
    {
        int times = 0;
        for(int i = 0; i < length; ++i)
        {
            if(numbers[i] == number)
                times++;
        }
     
        bool isMoreThanHalf = true;
        if(times * 2 <= length)
        {
            g_bInputInvalid = true;
            isMoreThanHalf = false;
        }
    
        return isMoreThanHalf;
    }
    

      

  • 相关阅读:
    loadrunne-- Analysis 分析器
    Fiddler抓包工具详细介绍
    在 Windows 10 x64 上安装及使用 ab 工具的流程
    Ab工具基本使用
    ab压测返回结果解析
    VMware Workstation 14 Pro永久激活密钥
    通用接口测试用例设计
    线段树の二 区间乘+区间加
    线段树の一 区间和
    C++位运算
  • 原文地址:https://www.cnblogs.com/xwz0528/p/4832473.html
Copyright © 2011-2022 走看看