码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] NO. 169 Majority Element

时间:2016-08-18 06:22:33      阅读:163      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!