169. Majority Element

LeetCode Majority Element【Easy】

  • 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.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

解决

题目的意思是给定一个给定的数组中,找出多数的元素,假定数组长度为n,则这个多数元素定义为该元素在数组中出现的次数大于[n/2]次。
这里给出两种解决办法,代码和部分的注释如下。

hash法

 /**
   * 使用map key 存储数组,value 统计出现的次数
   * @param nums
   * @return
   */
  public int majorityElement(int[] nums) {
      Map<Integer,Integer> map = new HashMap<>();
      int res =0;
      for(int i:nums){
          map.put(i,map.get(i)==null?1:map.get(i).intValue()+1);
          if(map.get(i).intValue()>(nums.length/2)){
              res=i;
          }

      }
      return res;
  }

数组方法

 /**
     * 排序,取数组mid,最后返回num[mid]值即为结果
     * @param nums
     * @return
     */
    public int majorityElement2(int[] nums) {
        Arrays.sort(nums);
        int t = nums.length/2;
        return nums[t];
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,087评论 0赞 10
  • Description Given an array of size n, find the majority e...
    Nancyberry阅读 187评论 0赞 0
  • MicrosoftOffice2003+以前的版本,默认格式:.doc (Word) .xls (Excel) ....
    盐果儿阅读 3,096评论 0赞 2
  • 说起来真的是罪过,小学时期每一次清明节我都感觉像是春游,少有肃穆追怀的氛围。 那时,每逢清明,学校会安排烈...
    凌岭阅读 393评论 0赞 1
  • 清明独酌小记 沽清末 忆先人 影如漫天纸灰有形而无相 在心头却又若阳光下纸上墨迹 斑驳的刺眼 孤伤 穿肠而过的黄汤...
    移步观景阅读 300评论 0赞 0

友情链接更多精彩内容