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;
    }
    

      

  • 相关阅读:
    三.php变量赋值和销毁
    四.php运算符(1)算术运算符
    四.php运算符(2)比较运算符
    四.php运算符(4)逻辑运算符
    extjs与后台交互
    EXT2.0 form实例
    SQL Server 2005 中的计算字段
    extJSitemselector的使用
    操作二进制数据
    Extjs Itemselector的使用示例
  • 原文地址:https://www.cnblogs.com/xwz0528/p/4832473.html
Copyright © 2011-2022 走看看