美文网首页
数组中出现次数超过一半的数字

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

作者: 赵老拖 | 来源:发表于2022-02-24 00:36 被阅读0次

描述

给一个长度为 n 的数组,数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。

示例1

输入:
[1,2,3,2,2,2,5,4,2]
复制
返回值:2

想法:因为出现次数超过数组长度一半,那数组排序后,数组中间数字是目标值

import java.util.*;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        Arrays.sort(array);
        int length = array.length;
        return array[length/2];
    }
}

相关文章

网友评论

      本文标题:数组中出现次数超过一半的数字

      本文链接:https://www.haomeiwen.com/subject/dsaalrtx.html