数字在排序数组中出现的次数

133 阅读1分钟

数字在排序数组中出现的次数

统计一个数字在排序数组中出现的次数。

例如输入排序数组[1, 2, 3, 3, 3, 3, 4, 5]和数字3,由于3在这个数组中出现了4次,因此输出4。

样例
输入:[1, 2, 3, 3, 3, 3, 4, 5] ,  3
输出:4

Map

时间复杂度O(n)

class Solution {
    public int getNumberOfK(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap();
        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);
            }
        }
        if(map.get(k) != null){
            return map.get(k);
        }
        return 0;
    }
}