机票统计
记票统计
http://www.nowcoder.com/questionTerminal/3350d379a5d44054b219de7af6708894
这里只要注意审题,别的没什么难点。比如题目要求按照候选人的输入顺序输出结果,假设我们使用了HashMap来存储,那么直接遍历HashMap是不对的,因为HashMap并不能保证输入的顺序,使用LinkedHashMap可以解决这个问题。或者像我这样,干脆根据String[]的顺序来输出,通常认为LinkedHashMap没有HashMap的性能高,但是在这里有脱裤子放屁的嫌疑,不管用哪个都不会差太多。
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextInt()) { //初始化 int numOfCandidates = in.nextInt(); in.nextLine();//指针移到下一行开头 String[] nameOfCandidates = in.nextLine().split(" "); int numOfVotes = in.nextInt(); in.nextLine();//指针移到下一行开头 String[] voteFor = in.nextLine().split(" "); Map<String,Integer> dict = new HashMap<>(); int invalid = 0; for(int i = 0; i < numOfCandidates; i++){ dict.put(nameOfCandidates[i],0); } //计数 for(int j = 0; j < numOfVotes; j++){ if(!dict.containsKey(voteFor[j])){ invalid++; } else{ Integer pre = dict.get(voteFor[j]); dict.put(voteFor[j],pre + 1); } } //输出结果 StringBuilder res = new StringBuilder(); for(String s : nameOfCandidates){ res.append(s); res.append(" : "); res.append(dict.get(s)); res.append("\n"); } res.append("Invalid : "); res.append(invalid); System.out.println(res); } } }