LeetCode 169 多数元素(Java实现)

题目描述:

题目描述


方法一(暴力法,最简单想到的):
不先把数组排个序,大概耗时2200多ms
排序之后大概耗时2100多ms。
代码:

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        Arrays.sort(nums);
        for(int i = 0;i < nums.length;i++){
    
    
            int count = 0;
            for(int j = 0;j < nums.length;j++){
    
    
                if(nums[i] == nums[j]){
    
    
                    count++;
                }
            }
            if(count > nums.length / 2){
    
    
                return nums[i];
            }
        }
        return -1;
    }
}

结果:

结果

方法二(排序):
题意
这句话说明了数组经过排序之后,数组下标n/2(向下取整时)一定是多数元素。
代码:

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

结果:

结果


方法三(Map):

代码:

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(Integer num : nums){
    
    
            if(!map.containsKey(num)){
    
    
                map.put(num,1);
            }else{
    
    
                map.put(num,map.get(num)+1);
            }
        }
        Map.Entry<Integer,Integer> majorityEntry = null;
        for(Map.Entry<Integer,Integer> entry : map.entrySet()){
    
    
            if(majorityEntry == null || entry.getValue() > majorityEntry.getValue()){
    
    
                majorityEntry = entry;
            }
        }
        return majorityEntry.getKey();
    }
}

结果:

扫描二维码关注公众号,回复: 12236187 查看本文章

结果

猜你喜欢

转载自blog.csdn.net/weixin_43752257/article/details/110715009
今日推荐