zoukankan      html  css  js  c++  java
  • 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 ar

    Java:

    public class Solution {
        public int majorityElement(int[] num) {
            Map<Integer,Integer>num_map=new HashMap<Integer,Integer>();
            int array_size=num.length;
            for(int i=0;i<array_size;i++){
                if(!num_map.containsKey(num[i])){
                    num_map.put(num[i],1);
                }
                else{
                    int temp=num_map.get(num[i]);
                    num_map.put(num[i],temp+1);
                }
            }
            Set<Integer>keys=num_map.keySet();
            int count=0;
            int result=0;
            for(int key:keys){
                if(num_map.get(key)>count){
                    count=num_map.get(key);
                    result=key;
                }
            }
            return result;
        }
    }

    C++

    class Solution {
    public:
        int majorityElement(vector<int> &num) {
            int n = num.size();  
            sort(num.begin(),num.end());  
            return num[n/2]; 
        }
    };
  • 相关阅读:
    bom案例2-弹出层
    bom案例1-div拖拽
    bom-scroll
    bom-client
    bom-offset
    9. 阻塞队列
    8. 读写锁
    7. CountDownLatch、CyclicBarrier、Semaphore
    6. Callable
    5. 集合不安全
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4209711.html
Copyright © 2011-2022 走看看