首页 > 其他 > 详细

[LeetCode] NO. 169 Majority Element

时间:2016-08-18 06:21:48      阅读:228      评论:0      收藏:0      [点我收藏+]

[题目] 

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.

 

[题目解析] 根据题目需要求数组中,出现次数过半的元素。最容易想到的就是直接的去遍历数组计数,然后出现次数过半的即为所求。

 public int majorityElement(int[] nums) {
       int result = 0;
       HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
       for(int i = 0; i < nums.length; i++){
           int num = nums[i];
           if(map.containsKey(num)){
               map.put(num, map.get(num) + 1);
           }else{
               map.put(num,1);
           }
           f(map.get(num) > (nums.length)/2){
               result = num;
           }
       }
       return result;
  }

还有没有其他方法呢?比较容易能想到,如果是一个有序数组,那么中间位置的数一定就是所求。我们可以对数组进行排序。

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

此外,还有一种比较巧妙的方法。

[LeetCode] NO. 169 Majority Element

原文:http://www.cnblogs.com/zzchit/p/5782497.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!