Title Description:
Xiao Ming is a careless, one day he went to the supermarket bought a number of chopsticks (n<20) The length of the chopsticks are not the same, he put all the chopsticks in the shopping bag to take home, the road accidentally missed a
Please use the program to help him find out how long the missing chopsticks are.
Input: Remaining chopsticks array, such as: 1, 2, 3, 2, 1, 3, 2
Return value: The length of the missing chopsticks, such as the input returned: 2 (when the input of the chopsticks data abnormal return-1, such as: Can not find missing chopsticks)
Problem-solving ideas: Using HashMap to the type of chopsticks and the number of key pairs of matching storage, when the repetition of chopsticks, the corresponding number of chopsticks +1, and then traverse a hashmap, to obtain the number of chopsticks,
If it is odd, it is missing chopsticks.
The code is as follows:
public class xiaoming_kuaizi{/** * @param args */public static void main (string[] args) {int[] chopsticks={1,2,3,2,1,3,2}; System.out.println (Checkchopsticks (chopsticks));} /** * Xiao Ming is a careless, one day he went to the supermarket to buy a number of chopsticks (n<20) * The length of the chopsticks are not the same, he put all the chopsticks in the shopping bag to take home, the road accidentally missed a root * Please use the program to help him find out how long the missing chopsticks are. * * * * @param chopsticks remaining chopsticks array, such as: 1, 2, 3, 2, 1, 3, 2 * @return int missing chopsticks length, as above input returned: 2 (returned when input chopsticks data is abnormal) -1, such as: Can not find missing chopsticks) * * /public static int checkchopsticks (int[] chopsticks) { Map<integer, Integer> hm=new hashmap<integer,integer> (); int count=0; for (int i = 0; i < chopsticks.length; i++) {if (Hm.containskey (Chopsticks[i])) {count=hm.get (chopsticks[i]) +1;} Else{count=1;} Hm.put (Chopsticks[i], count);} for (int i = 0; i < chopsticks.length; i++) {if (Hm.get (Chopsticks[i])%2==0) {continue;} else if (Hm.get (Chopsticks[i])%2!=0) {return chopsticks[i];}} return-1;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
2015 Huawei Machine Test--Xiao Ming's chopsticks