小明和完美序列(HashMap、Map、Entry)
小明和完美序列
知识点:
//导包:HashMap、Map、Entry
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;public class Main {public static void main(String [] args) {
//创建Map(HashMap)对象 Map<Integer,Integer> map = new HashMap<>();
//put方法用来添加key和valuemap.put(1, 2);
//get方法可以获取当前key值对应的value值System.out.println(map.get(2));
//size方法可以知道目前的键值对数目System.out.println(map.size());
//创建Entry对象
//entrySet方法可以获取map集合中的键值对for(Entry<Integer,Integer>entry:map.entrySet()) {
//entry.getKey()和entry.getValue()来遍历key和valueSystem.out.println(entry.getKey()+" "+entry.getValue());}
//getOrDefault(k,默认值)方法是返回k的value值,如果没有value值则返回默认值。System.out.print(map.getOrDefault(3, 1));}
}
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Map.Entry;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int[] arr = new int[n];for(int i=0;i<n;i++) {arr[i] = sc.nextInt();}Map<Integer,Integer> map = new HashMap<>();for(int x:arr) {map.put(x,map.getOrDefault(x,0)+1);}int t = 0;for(Entry<Integer,Integer> entry:map.entrySet()) {if(entry.getKey() != entry.getValue()) {if(entry.getKey() > entry.getValue()) {t+=entry.getValue();}else {t+=(entry.getValue()-entry.getKey()); }}}System.out.print(t);}
}