题解 | #牛群共有的编号#
牛群共有的编号
https://www.nowcoder.com/practice/a188da7b9c3a408b98b1cf47632f59d0?tpId=363&tqId=10609084&ru=/exam/oj&qru=/ta/super-company23Year/question-ranking&sourceUrl=%2Fexam%2Foj
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型二维数组
* @return int整型一维数组
*/
public int[] common_cow_numbers (int[][] nums) {
// 创建hashMap存储数值以及出现的次数
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int[] num : nums) {
for (int i = 0; i < num.length; i++) {
hashMap.put(num[i],hashMap.getOrDefault(num[i],0)+1);
}
}
ArrayList<Integer> arrayList = new ArrayList<>();
Set<Map.Entry<Integer, Integer>> entries = hashMap.entrySet();
for (Map.Entry<Integer, Integer> entry : entries) {
Integer value = entry.getValue();
if(value==nums.length){
arrayList.add(entry.getKey());
}
}
Collections.sort(arrayList);
int [] result = new int [arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
result[i] = arrayList.get(i);
}
return result;
}
}
本题知识点分析:
1.哈希表
2.API函数(Collections.sort)
3.有序集合存取
4.集合转数组
5.数学模拟
本题解题思路分析:
1.一开始我把nums.length做成3,不是通用的解法
2.所以要注意nums.length可以是任意长度,多个数组
3.将单个数组中的每个元素,添加到hashMap中,并记录出现的数值和出现的次数。
4.遍历hashMap,从entry中取出value,如果当前value等于nums.length,比如3个数组,那么value为3
5.将符合条件的value,取key,添加到arrayList集合中,利用Collections.sort升序
6.集合转数组进行返回

查看6道真题和解析