题目如下:
代码如下:
package huawei; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Demo { public static int checkChopsticks(int[] chopsticks) { /* * map的key作为筷子的长度,value作为筷子的个数 */ 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;//筷子个数加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; } public static void main(String[] agrs) { Scanner cin = new Scanner(System.in); String input = cin.nextLine(); String[] string = input.split(","); int[] inputInt = new int[string.length]; for (int i = 0; i < string.length; i++) { inputInt[i] = Integer.parseInt(string[i]); } int n = checkChopsticks(inputInt); System.out.println(n); } }
时间: 2024-10-09 00:49:01