MajorityElement_leetcode169

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

Example 1:code

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

Example 2:element

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

實現:get

//使用map來實現 一個蘿蔔一個坑  
public static int majorityElement(int[] nums) {
    Map<Integer,Integer> map = new HashMap<Integer, Integer>();
    int n =-1;
    for (int i=0;i<nums.length;i++){
        if(map.containsKey(nums[i])){
            int value = map.get(nums[i])+1;
            map.put(nums[i],value);
        }else{
            map.put(nums[i],1);
        }
    }
    //這裏遍歷有不少方法啦
    Set<Integer> set = map.keySet();
    Iterator<Integer> iterator = set.iterator();
    int num = nums.length/2;
    while(iterator.hasNext()){
         n = iterator.next();
         if(map.get(n) > num){
             return n;
         }
    }

   return n;
}

// Moore voting algorithm 摩爾投票算法
public static int majorityElement2(int[] nums) {
    int count=0, ret = 0;
    for (int num: nums) {
        if (count == 0) {
            ret = num;
        }
        if (num != ret) {
            count--;
        } else {
            count++;
        }
    }
    return ret;
}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息