题解 | #农场牛的标识III# java
农场牛的标识III
https://www.nowcoder.com/practice/f8cf74a21aa4440595f007789ea6bd61
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型 */ public int twoCountNumber (int[] nums) { // write code here HashMap<Integer, Integer> countMap = new HashMap<>(); // 统计每个标识出现的次数 for (int num : nums) { countMap.put(num, countMap.getOrDefault(num, 0) + 1); } // 遍历计数映射,找到只出现两次的牛的标识 for (HashMap.Entry<Integer, Integer> entry : countMap.entrySet()) { if (entry.getValue() == 2) { return entry.getKey(); // 返回只出现两次的牛的标识 } } return 1; // 默认返回 1,可能需要根据实际需求调整 } }
Java代码
代码主要考察了以下几个知识点:
- HashMap
- 循环遍历和条件判断
该题的代码其实不太难,主要是思想不好想而已啦。代码的解释主要写到注解了。HashMap做统计次数,然后遍历映射即可。