LeetCode169 多数元素

题目

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

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

示例 1:

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

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


进阶:

尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。

方法

哈希法

class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        int length = nums.length;
        if(nums==null||length==0){
            return 0;
        }
        if(length==1){
            return nums[0];
        }
        int res = 0;
        for(int num:nums){
            if(map.containsKey(num)){
                map.put(num,map.get(num)+1);
                if(map.get(num)>length/2){
                    res = num;
                    break;
                }

            }else{
                map.put(num,1);
            }
        }
        return res;
    }
}

排序法

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        int len = nums.length;
        return nums[len/2];
    }
}

分治法

投票法

class Solution {
    public int majorityElement(int[] nums) {
        if(nums==null||nums.length==0){
            return 0;
        }
        int currentNum = nums[0];
        int count = 0;
        for(int num:nums){
            if(count==0){
                currentNum = num;
                count = 1;
            }else{
                if(currentNum==num){
                    count++;
                }else{
                    count--;
                }
            }
        }
        return currentNum;
    }
}
posted @ 2021-06-15 20:39  你也要来一颗长颈鹿吗  阅读(28)  评论(0)    收藏  举报