Skip to content
New issue

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

LC双周赛 —6300. 最小公共值 #22

Open
HealUP opened this issue May 11, 2023 · 0 comments
Open

LC双周赛 —6300. 最小公共值 #22

HealUP opened this issue May 11, 2023 · 0 comments
Labels
算法 记录刷题记录,代码随想录

Comments

@HealUP
Copy link
Owner

HealUP commented May 11, 2023

##第 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;
    }
}
@HealUP HealUP added 算法 记录刷题记录,代码随想录 哈希法 labels May 11, 2023
@HealUP HealUP removed the 哈希法 label Jul 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 记录刷题记录,代码随想录
Projects
None yet
Development

No branches or pull requests

1 participant