天天看點

劍指Offer-數組出現次數超過一半的數字

Description:

數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。例如輸入一個長度為9的數組{1,2,3,2,2,2,5,4,2}。由于數字2在數組中出現了5次,超過數組長度的一半,是以輸出2。如果不存在則輸出0。

  • 時間限制:1秒
  • 空間限制:32768K
Java
import java.util.Map;
import java.util.HashMap;

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int a: array) {
            count.put(a, count.getOrDefault(a, 0) + 1);
        }
        for (int key: count.keySet()) {
            if (count.get(key) > array.length / 2) {
                return key;
            }
        }
        return 0;
    }
}