题目:在排序数组中查找数字
举例:
输入数组{1,2,3,3,3,3,4,4,5}和数字3,因为3在数组中出现了4次,所以输出4;
思路: 使用哈希统计
class Main53 {
public static void main(String[] args) {
int[] array = {1,2,3,3,3,3,4,5};
System.out.println(count(array, new Scanner(System.in).nextInt()));
}
private static int count(int[] array, int key) {
if (array == null || array.length == 0)return -1;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < array.length; i++) {
map.merge(array[i], 1, Integer::sum);
}
return map.get(key);
}
}