题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param k int整型 * @return int整型 */ public int GetNumberOfK (int[] nums, int k) { // write code here if (nums.length == 0) { return 0; } // 排序 Arrays.sort(nums); // 记录元素出现次数 HashMap<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); } } // 获取k出现的数 if (map.containsKey(k)) { return map.get(k); } else { return 0; } } }