leetcode169. 求众数

版权声明:本文为博主原创文章,未经博主允许不得转载。有任何问题请邮件联系[email protected] https://blog.csdn.net/drdongshiye/article/details/85698568

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

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

示例 1:

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

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

public int majorityElement(int[] nums) {
   if (1 == nums.length) {
        return nums[0];
    }
    int i;
    int length = nums.length;
    Map<Integer, Integer> map = new TreeMap<>();
    for (i = 0; i < length; i++) {
        map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
    }
    List<Map.Entry<Integer,Integer>> list = new ArrayList<>(map.entrySet());
    Collections.sort(list,(o1,o2)->(o2.getValue()-o1.getValue()));
    return list.get(0).getKey();
}

更优秀的方式

class Solution {
    public int majorityElement(int[] nums) {
        int length = nums.length;
        if(length == 1) return nums[0];
        int count = 1, maj = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                maj = nums[i];
            }
            if (maj != nums[i]) {
                count--;
            } else {
                count++;
            }
        }
        return maj;
    }
}

更简单的方式

public int majorityElement1(int[] nums) {
            Arrays.sort(nums);
            return nums[nums.length/2];
        }

猜你喜欢

转载自blog.csdn.net/drdongshiye/article/details/85698568
今日推荐