题解 | #不同的体重#
不同的体重
https://www.nowcoder.com/practice/4a6411ef749445e88baf7f93d1458505
考察Hash表的用法
根据这道题目,使用一个哈希表存储所有类别的牛的重量和对应的个数,随后从中取出个数判断是否有一样的,有的话返回false。
Java代码如下所示
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param arr int整型一维数组 * @return bool布尔型 */ public boolean uniqueOccurrences (int[] arr) { // write code here HashMap<Integer,Integer> map = new HashMap<>(); // 重量:对应的个数 for(int num:arr){ if(map.containsKey(num)){ map.put(num,map.get(num)+1); }else{ map.put(num,1); } } HashSet<Integer> set = new HashSet<>(); for(int num:map.values()){ if(set.contains(num)) return false; else set.add(num); } return true; } }