首页 > 其他 > 详细

169-求众数

时间:2019-05-06 19:12:10      阅读:144      评论:0      收藏:0      [点我收藏+]
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3

示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2


解法1:
public static int majorityElement(int[] nums) {
        Map<Integer,Integer> map=new HashMap<>();
        for (int a:nums)
        {
            map.put(a,map.containsKey(a)?map.get(a)+1:1);
        }
        int n=nums.length;
        int temp=0;
        for (int i=0;i<nums.length;i++)
        {
            if (map.get(nums[i])>n/2)
            {
                temp=nums[i];
                break;
            }
        }
       return temp;
    }

解法2:
public static int majorityElement(int[] nums) {
        int count=1;
        for (int i=1;i<nums.length;i++) {
            if (nums[0]==nums[i]) {
                count++;
            }else {
                count--;
        }
        if (count<0)
        {
            count=1;
            nums[0]=nums[i];
        }
      }
          return nums[0];
      }

 

169-求众数

原文:https://www.cnblogs.com/dloading/p/10821405.html

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