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

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

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

import java.util.Arrays;

public class Solution {
    public int MoreThanHalfNum_Solution(int[] array) {
        int temp = array[0];
        int count = 1;
        for (int i = 1; i < array.length; i++) {
            if (array[i] == temp) {
                count++;
            } else if (count > 0) {
                count--;
            } else {
                //count 已被减为0
                temp = array[i];
                count++;
            }
        }

        //重置为0
        count = 0;
        for (int i = 0; i < array.length; i++) {
            if (temp == array[i]) {
                count++;
            }
        }
        if (count >= array.length / 2) {
            return temp;
        }
        return 0;

    }
}
全部评论

相关推荐

2025-12-22 15:04
江西农业大学 Web前端
SaviorSu:直接说下学期可以请假,一般情况学校允许我26届,大三就直接去实习了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务