LeetCode --- 求众数

给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在众数。

示例 1:

输入: [3,2,3]
输出: 3

示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

public class MajorityElement {

    @Test
    public void test() {
        Assert.assertEquals(2, majorityElement(new int[] {2,2,1,1,1,2,2}));
    }

    public int majorityElement(int[] nums) {
        Map<Integer, Long> collect = Arrays.stream(nums).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        int length = nums.length / 2;
        for (Map.Entry entry : collect.entrySet()) {
            if ((Long)entry.getValue() > length) {
                return (int)entry.getKey();
            }
        }

        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/ydonghao2/article/details/80419078