zoukankan      html  css  js  c++  java
  • (Array)169. Majority Element

    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 class Solution {      //更好的方法是排序,return 中间那个数
        public int majorityElement(int[] nums) {
         	Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    		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);
    		}
    		Set set = map.entrySet();
    		Iterator it = set.iterator();
    		int res = 0;
    		while (it.hasNext()) {
    			Map.Entry entry = (Map.Entry) it.next();
    			if ((int) entry.getValue() > nums.length / 2)
    				res = (int) entry.getKey();
    		}
    		return res;
        }
        
    }
    

      

  • 相关阅读:
    AI ResNet V1
    Lua基础
    git命令小结
    定时器及时间轮
    expect
    vscode 常用快捷键
    动态链接库与共享内存:
    container_of机制
    ELF文件格式
    git学习补充
  • 原文地址:https://www.cnblogs.com/kydnn/p/5380766.html
Copyright © 2011-2022 走看看