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

来源:互联网 发布:淘宝网上买红酒靠谱吗 编辑:程序博客网 时间:2024/06/06 23:48

题目描述

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

<分析>(推荐使用解法二,时间复杂度较低)
解法一:一开始首先想到的是暴力破解
             遍历只需要遍历到数组的长度一半位置即可,因为后序不可能再出现数字超过数组长度的一半。
             每当遇到相同的数字则count++
             遍历结束判断count是否大于数组长度的一半,大于则返回该数字

解法二:采用阵地攻守的思想
             第一数字作为第一个士兵,守阵地,count=1;
             遇到相同的数字就count++;
             遇到不同数字,就是敌人,那么同归于尽,count--,当遇到count==0,就以当前值为士兵守阵地;
             继续下去,到最后如果士兵数count大于0,那么有可能是主元素。
             再加一次循环,判断这个士兵的个数是否大于数组一半的长度即可。
/** *  * @author zy * @date 2017年10月4日 下午7:23:50 * @Decription 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。 *             由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。 */public class Ex18 {public int MoreThanHalfNum_Solution(int[] array) {/** * 解法一 *///int result = 0;//if (array.length == 0) {//return result;//}//int halflength = array.length / 2;//for (int i = 0; i <= halflength; i++) {//int count = 1;//for (int j = i + 1; j < array.length; j++) {//if (array[j] == array[i]) {//count++;//}//}//if (count > halflength) {//return array[i];//}//}//return result;/** * 解法二 */int result = 0;if (array.length == 0) {return result;}int halflength = array.length/2;int count = 1;int temp = array[0];for(int i = 1;i<array.length;i++){if (count == 0) {temp = array[i];}if (array[i] == temp) {count++;}else {count--;}}if (count > 0) {count = 0;for (int i = 0; i < array.length; i++) {if (array[i] == temp) {count++;}}if (count>halflength) {return temp;}}return result;}}




阅读全文
0 0
原创粉丝点击