[刷题防痴呆] 0169 - 多数元素 (Majority El

2022-01-06  本文已影响0人  西出玉门东望长安

题目地址

https://leetcode.com/problems/majority-element/

题目描述

169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:

Input: [3,2,3]
Output: 3
Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

思路

求一个数在数组出现的次数大于数组总长的二分之一, 可以排序, 然后取 length / 2的元素. 也可以hashmap. 也可以用计数法. 计数法代码最简单.

关键点

代码

// 方法1: 排序. 
class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        
        return nums[nums.length / 2];
    }
}

// 方法2: HashMap
class Solution {
    public int majorityElement(int[] nums) {
        int n = nums.length;
        Map<Integer, Integer> map = new HashMap<>();
        for (int num: nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        for (int key: map.keySet()) {
            if (map.get(key) > n / 2) {
                return key;
            }
        }

        return -1;
    }
}

// 方法3: 计数法
class Solution {
    public int majorityElement(int[] nums) {
        int candidate = 0;
        int count = 0;
        
        for (int num: nums) {
            if (candidate == num) {
                count++;
            } else {
                if (count == 0) {
                    candidate = num;
                    count++;
                } else {
                    count--;
                }
            }
        }
        
        return candidate;
    }
}

// 如果需要验证
class Solution {
    public int majorityElement(int[] nums) {
        int count = 0;
        int candidate = -1;

        for (int num: nums) {
            if (num == candidate) {
                count++;
            } else {
                if (count == 0) {
                    candidate = num;
                    count++;
                } else {
                    count--;
                }
            }
        }

        int len = nums.length / 2;
        count = 0;
        for (int num: nums) {
            if (num == candidate) {
                count++;
            }
        }

        if (count > len) {
            return candidate;
        }
        return -1;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读