Leetcode:169. Majority Element(找到数组中出现次数最多的元素)

来源:互联网 发布:药物实验志愿者知乎 编辑:程序博客网 时间:2024/06/05 15:30

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.

分析:拿到这题,很有可能会理解出错,那就是找出数组里面出现次数超过n/2次的,而不是找出出现次数最多的。
一开始我就理解错了题意。
基于这个,借助java封装的函数可写出下面简洁代码:

Method1:

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

Method2

这是我看别人写的,感觉这个方法很完美。

    public int majorityElement(int[] num) {        int major=num[0], count = 1;        for(int i=1; i<num.length;i++){            if(count==0){                count++;                major=num[i];            }else if(major==num[i]){                count++;            }else count--;        }        return major;    }

Method3

Disscuss里面的答案:感觉这个蛮符合逻辑 比较容易想到。

// Hashtable public int majorityElement2(int[] nums) {    Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();    //Hashtable<Integer, Integer> myMap = new Hashtable<Integer, Integer>();    int ret=0;    for (int num: nums) {        if (!myMap.containsKey(num))            myMap.put(num, 1);        else            myMap.put(num, myMap.get(num)+1);        if (myMap.get(num)>nums.length/2) {            ret = num;            break;        }    }    return ret;}
阅读全文
0 0
原创粉丝点击