zoukankan      html  css  js  c++  java
  • LeetCode 169. Majority Element Java

    题目:

    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.

    题意:给出一个长度为n的数组,查找其中的主要元素。主要元素即在数组中出现次数大于n/2的元素。题目假设数组不为空而且主要元素一定存在。最简单的方法就是使用一个hashMap存储元素出现的次数,然后遍历hashMap找出value大于n/2的key。

    代码(使用hashMap的方法):

    public class Solution {
    
    	public int majorityElement(int[] nums) {
    		HashMap<Integer, Integer> res=new HashMap<>();
    		for(int i=0;i<nums.length;i++){
    			if(res.containsKey(nums[i])){
    				int val=res.get(nums[i]);
    				res.remove(nums[i]);
    				res.put(nums[i], val+1);
    			}else{
    				res.put(nums[i], 1);
    			};
    		}
    				
    		Iterator iter = res.entrySet().iterator();
    		while (iter.hasNext()) {
    			Map.Entry entry = (Map.Entry) iter.next();
    			Object key = entry.getKey();
    			Object val = entry.getValue();
    			if((int)val>nums.length/2){
    				System.out.println(key);
    				return (int)key;
    			}
    		}
    		
    		return 0;
    	}
    }
  • 相关阅读:
    前端HTMLCSS
    jedis 连接池的使用
    win8+安装net3.5步骤与常见错误.
    并行线程的生命周期
    OneNote截图快捷键冲突解决方案
    C#中lsitView如何搜索某个子项
    redis哨兵与集群
    git笔记
    微软官方Hololens开发课程介绍
    Markdown使用入门简介
  • 原文地址:https://www.cnblogs.com/271934Liao/p/6907163.html
Copyright © 2011-2022 走看看