【C++算法学习——从两个数字数组里生成最小数字】

C++算法学习——从两个数字数组里生成最小数字

题目:

给你两个只包含 1 到 9 之间数字的数组 nums1nums2 ,每个数组中的元素 互不相同 ,请你返回 最小 的数字,两个数组都 至少 包含这个数字的某个数位。

示例 1:

输入:nums1 = [4,1,3], nums2 = [5,7]
输出:15
解释:数字 15 的数位 1 在 nums1 中出现,数位 5 在 nums2 中出现。15 是我们能得到的最小数字。

示例 2:

输入:nums1 = [3,5,2,6], nums2 = [3,1,7]
输出:3
解释:数字 3 的数位 3 在两个数组中都出现了。

提示:

  • 1 <= nums1.length, nums2.length <= 9
  • 1 <= nums1[i], nums2[i] <= 9
  • 每个数组中,元素 互不相同
初次解答:

双重for循环遍历,查找是否相同最小元素或寻找两个数组最小值

class Solution {
public:
    int minNumber(vector<int>& nums1, vector<int>& nums2) {
        int num1 = nums1[0], num2 = nums2[0];
        int temp_result = 10;
        int result = 0;
        bool flag = false;
        for(int i = 0; i < nums1.size(); ++i)
        {
            for(int j = 0; j < nums2.size(); ++j)
            {
                if(nums1[i] == nums2[j])
                {
                    num1 = nums1[i];
                    num2 = nums2[j];
                    if(temp_result > num1)
                    {
                        temp_result = num1;
                    }
                    flag = true;
                }
                if(num2 > nums2[j])
                {
                    num2 = nums2[j];
                }
            }
            if(num1 > nums1[i])
            {
                num1 = nums1[i];
            }
        }
        if(flag)
        {
            result = temp_result;
        }
        else{
            if(num1 > num2)
            {
                result = num2 * 10 + num1;
            }
            else if(num1 < num2)
            {
                result = num1 * 10 + num2;
            }
        }
        return result;
    }
};
题解:

思路:

1、如果nums1与nums2中有相同的数字,选出其中最小的那个即为答案。

将nums1中的所有元素放入一个哈希集合中,一次遍历nums2中的元素,判断其是否在哈希集合中。

2、如果nums1与nums2中没有相同的数字,分别取nums1和nums2的最小元素组成一个两位数xy或yx,比较xy和yx中的较小值。

class Solution {
public:
    int minNumber(vector<int>& nums1, vector<int>& nums2) {
        auto same = [&]() -> int{
            unordered_set<int> s(nums1.begin(), nums1.end());
            int x = 10;
            for(int num : nums2)
            {
                if(s.count(num))
                {
                    x = min(x, num);
                }
            }
            return x == 10? -1 : x;
        };
        
        if(int x == same(); x != -1)
        {
            return x;
        }
        
        int x = *min_element(nums1.begin(), nums1.end());
        int y = *min_element(nums2.begin(), nums2.end());
        
        return min(x*10+y, x+y*10);    
};

复杂度分析:

时间复杂度:O(m+n),其中 m 和 n 分别是数组 nums1和 nums2的长度。

空间复杂度:O(m),即为哈希表需要使用的空间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值