美文网首页LeetCode每日一题
LeetCode每日一题: 多数元素

LeetCode每日一题: 多数元素

作者: Patarw | 来源:发表于2020-08-05 08:26 被阅读0次

先说一下我的思路吧,就是利用HashMap存储数组里面的值和出现的次数,当出现次数大于n/2的时候就返回这个值即可,话不多说,直接上代码

  • 代码实现:
 class Solution {
public int majorityElement(int[] nums) {
  HashMap<String,Integer> map = new HashMap<>();
  int res = 0;
          for(int i = 0;i < nums.length;i++){    
              if(map.containsKey(nums[i] + "")){                     
                   map.put(nums[i] + "",map.get(nums[i] + "") + 1);                     
              }else{
                   map.put(nums[i] + "",1);
              }
              if(map.get(nums[i] + "") > nums.length / 2){
                     return nums[i];
                }
          }
    return -1;        
}
}

相关文章

网友评论

    本文标题:LeetCode每日一题: 多数元素

    本文链接:https://www.haomeiwen.com/subject/pwjprktx.html