Leetcode 169. Majority Element (第四周作业)

来源:互联网 发布:美国人性格 知乎 编辑:程序博客网 时间:2024/05/18 01:53

这周,我做了一道上课的时候老师讲过的众数的问题,不过我做得是easy级别的,下周我会做medium级别的。

先贴一下题意

众数的定义为一个数组中,这个数字出现超过总数的1/2,即为众数。

我选择偷个懒,用java的hashmap做这道题。

class Solution {    public int majorityElement(int[] nums) {        HashMap<Integer,Integer> my = new HashMap<>();        for(int i = 0; i < nums.length;i++){            Integer count = 0;            if(my.get(nums[i]) == null){                count = 1;            }            else{                count = my.get(nums[i]);                count++;            }            if(count > nums.length/2){                return nums[i];            }            else{                my.put(nums[i],count);            }        }        return -1;    }}

由于使用hashmap,所以平均来说时间复杂度为O(n),即为遍历一遍的时间复杂度。

空间复杂度为O(n),即使用了hashmap来存储这些数字和数目。

原创粉丝点击