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

来源:互联网 发布:淘宝外贸的衣服能买吗 编辑:程序博客网 时间:2024/06/05 12:10

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

package A28数组中出现次数超过一半的数;public class Solution {    public int MoreThanHalfNum_Solution(int[] array) {        if (array.length == 0) {            return 0;        }        int times = 0;        int result = array[0];        for (int i = 0; i < array.length; i++) {            if (times == 0) {                result = array[i];                times = 1;            }            if (result == array[i]) {                times++;            } else {                times--;            }        }        times = 0;        for (int i = 0; i < array.length; i++) {            if (result == array[i]) {                times++;            }        }        if (times * 2 <= array.length) {            result = 0;        }        return result;    }}
阅读全文
0 0