0
点赞
收藏
分享

微信扫一扫

给你一个长度为n的数组,其中有一个数字出现的次数至少为一半,找出这个数字

芝婵 2022-02-17 阅读 167
题目

给你一个长度为n的数组,其中有一个数字出现的次数至少为一半,找出这个数字

解法
   public static int getMajorElement(int[] arr) {
        if (arr == null || arr.length == 0) return 0;
        int candidate = -1; // 默认元素值
        int count = 0; // 计数器
        for (int j : arr) {
            if (count == 0) {
                candidate = j;
                count++;
            } else if (candidate == j) {
                count++;
            } else {
                count--;
            }
        }
        return candidate;
    }
举报

相关推荐

0 条评论