题解 | #数组中出现次数超过一半的数字#

数组中出现次数超过一半的数字

http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {

        int count = 1;
        int target = array[0];

        for (int i = 1; i < array.length; i++) {

            if (target == array[i]) {
                count++;
            } else {

                count--;

                //数字出现的次数超过数组长度的一半 最后count一定不为0 所以剩下的肯定时那个数
                if (count == 0) {
                    target = array[i];
                    count = 1;
                }
            }
        }

        return target;
    }
}
刷刷题 文章被收录于专栏

刷刷题 活跃活跃脑细胞

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务