数组中出现次数超过一半的数字
来源:互联网 发布:杭州藤木网络 编辑:程序博客网 时间:2024/05/23 01:14
题目:数组中有一个数字的出现次数超过数组长度的一半,请找出这个数字。
方法1:基于Partition函数的O(n)算法。其实就是求数组的中位数。先在数组中随机选择一个数字,然后调整数组中数字的顺序,使得比选中的数字小的数字都排在它的左边,比选中的数字大的数字都排在它的右边。如果这个选中的数字的下标刚好是n/2,那么这个数字就是数组的中位数。如果它的下标大于n/2,那么中位数应该位于它的左边,我们可以接着在它的左边部分的数组中查找。如果它的下标小于n/2,那么中位数应该位于它的右边,我们可以接着在它的右边部分的数组中查找。
int MoreThanHalfNum(int* numbers, int length){ if (CheckInvalidArray(numbers, length)){ return 0; } int middle = length >> 1; int start = 0; int end = length - 1; int index = Partition(numbers, length, start, end); while (index != middle){ if (index > middle){ end = index - 1; index = Partition(numbers, length, start, end); } else { start = index + 1; index = Partition(numbers, length, start, end); } } int result = numbers[middle]; 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;}
方法2:遍历数组的时候保存两个值:一个是数组中的一个数字,一个是次数。当遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数+1;如果下一个数字和之前保存的数字不同,则次数减1。如果次数为零,需要保存下一个数字,并把次数设为1.由于我们要找的数字出现的次数比其他所有数字出现的次数之和还要多,那么要找的数字肯定是最后一次吧次数设为1时对应的数字。
int MoreThanHalfNum(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;}
测试用例:
- 功能测试(输入的数组中存在一个出现次数超过数组长度一般的数字,输入的数组中不存在一个出现次数超过数组长度一般的数字)
- 特殊输入测试(输入的数组中只有一个数字、输入NULL指针)
0 0
- 数组中超过出现次数超过一半的数字
- 74.数组中超过出现次数超过一半的数字
- 74 数组中超过出现次数超过一半的数字
- 【数组4】数组中出现次数超过一半的数字
- 数组4:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 找出数组中出现次数超过长度一半的数字
- 2-数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字[算法]
- 数组中出现次数超过一半的数字
- 找出数组中出现次数超过一半的数字--百度
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 寻找数组中出现次数超过一半的数字
- 面试训练数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- Basic Circuits - Bypass Capacitors
- 如何计算时间复杂度
- 用Python学习统计学基础-6
- dos下的基本命令
- Http协议 头文件
- 数组中出现次数超过一半的数字
- webservice获取天气预报异常
- Dynamic Time Warping 动态时间规整算法
- 移动虚拟机后修改 MAC 地址
- 2015史上最全android手机root刷机工具排行榜
- noip 近年分析
- 树
- MySQL安装过程
- MPChartLib绘制曲线图