题解 | #牛群的共同特征#
牛群的共同特征
https://www.nowcoder.com/practice/141441ef39364565b1b1b6614e594763?tpId=363&tqId=10605503&ru=/exam/oj&qru=/ta/super-company23Year/question-ranking&sourceUrl=%2Fexam%2Foj
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums1 int整型一维数组 * @param nums2 int整型一维数组 * @return int整型一维数组 */ public int[] intersection (int[] nums1, int[] nums2) { HashSet<Integer> hashSet = new HashSet<>(); HashSet<Integer> hashSet1 = new HashSet<>(); ArrayList<Integer> arrayList = new ArrayList<>(); for (int i = 0; i < nums1.length; i++) { hashSet.add(nums1[i]); } for (int i = 0; i < nums2.length; i++) { if(hashSet.contains(nums2[i])&&!hashSet1.contains(nums2[i])){ arrayList.add(nums2[i]); hashSet1.add(nums2[i]); } } 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.集合存取
3.API函数(Collection.sort)
4.数学模拟
本题解题思路分析:
1.创建hashSet用于存储不重复的nums1
2.创建hashSet1用于存储nums1和nums2的交集,并且不会重复的
3.遍历nums2时,需要同时满足存在交集并且hashSet1中不存在该值,因为重复值不用添加
4.集合排序
5.或者先转数组,再用API函数排序,Arrays.sort()
6.集合转数组也可以用Stream的mapToInt(Integer::intValue).toArray();
本题使用编程语言: Java
如果你觉得本篇文章对你有帮助的话,可以点个赞支持一下,感谢~