We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
##第 96 场
双周赛 —6300. 最小公共值
题目链接:https://leetcode.cn/contest/biweekly-contest-96/problems/minimum-common-value/
自己写的:
class Solution { public int getCommon(int[] nums1, int[] nums2) { //哈希法 set集合实现,因为无法判断输入数组的大小 浪费空间会比较大 //判断临界条件 // if ( nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) { // return -1;//返回-1 // } //存入nums1数组到set集合 Set<Integer> set = new HashSet<>(); for (int i : nums1) { set.add(i); } //存放结果集 Set<Integer> resSet = new HashSet<>(); //遍历nums2同时判断nums1的集合中否存在这个元素,存在的放入resSet中 for (int i : nums2) { if (set.contains(i)) { resSet.add(i); } } //返回数组的第一个元素 int[] res = resSet.stream().mapToInt(x -> x).toArray(); if (res != null && res.length != 0) { Arrays.sort(res);//升序 return res[0]; } else { return -1; } } }
优化:因为题目告诉我们,它们已经按非降序排序(即已按升序排序)不用将交集放到另外一个集合了,直接第一个找到了就返回该数就好。
class Solution { public int getCommon(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<Integer>(); for (int num : nums1) { set.add(num); } for (int num2 : nums2) { if (set.contains(num2)) { return num; } } return -1; } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
##第 96 场
双周赛 —6300. 最小公共值
题目链接:https://leetcode.cn/contest/biweekly-contest-96/problems/minimum-common-value/
自己写的:
优化:因为题目告诉我们,它们已经按非降序排序(即已按升序排序)不用将交集放到另外一个集合了,直接第一个找到了就返回该数就好。
The text was updated successfully, but these errors were encountered: