classSolution { public: intminNumber(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()); returnmin(x * 10 + y, y * 10 + x); } };
publicclassSolution { publicintMinNumber(int[] nums1, int[] nums2) { int s = Same(nums1, nums2); if (s != -1) { return s; } int x = nums1.Min(); int y = nums2.Min(); return Math.Min(x * 10 + y, y * 10 + x); }
publicintSame(int[] nums1, int[] nums2) { ISet<int> s = new HashSet<int>(); foreach (int num in nums1) { s.Add(num); } int x = 10; foreach (int num in nums2) { if (s.Contains(num)) { x = Math.Min(x, num); } } return x == 10 ? -1 : x; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defminNumber(self, nums1: List[int], nums2: List[int]) -> int: defsame() -> int: s = set(nums1) & set(nums2) return -1ifnot s elsemin(s) if (x := same()) != -1: return x x = min(nums1) y = min(nums2) returnmin(x * 10 + y, y * 10 + x)
intsame(int* nums1, int nums1Size, int* nums2, int nums2Size) { HashItem *set = NULL; for (int i = 0; i < nums1Size; i++) { hashAddItem(&set, nums1[i]); } int x = 10; for (int i = 0; i < nums2Size; i++) { if (hashFindItem(&set, nums2[i])) { x = fmin(x, nums2[i]); } } hashFree(&set); return x == 10 ? -1 : x; }
intminNumber(int* nums1, int nums1Size, int* nums2, int nums2Size) { int count = same(nums1, nums1Size, nums2, nums2Size); if (count != -1) { return count; } int x = INT_MAX, y = INT_MAX; for (int i = 0; i < nums1Size; i++) { x = fmin(x, nums1[i]); } for (int i = 0; i < nums2Size; i++) { y = fmin(y, nums2[i]); } return fmin(x * 10 + y, y * 10 + x); }
funcminNumber(nums1 []int, nums2 []int)int { var same = func()int { s := make(map[int]bool) x := 10 for _, num := range nums1 { s[num] = true } for _, num := range nums2 { if _, ok := s[num]; ok { x = min(x, num) } } if x == 10 { return-1 } return x }
if x := same(); x != -1 { return x; } x, y := nums1[0], nums2[0] for _, num := range nums1 { x = min(x, num) } for _, num := range nums2 { y = min(y, num) } return min(x * 10 + y, y * 10 + x) }
funcmin(x int, y int)int { if x > y { return y } return x }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var minNumber = function(nums1, nums2) { constsame = () => { const s = newSet(nums1); let x = 10; for (const m of nums2) { if (s.has(m)) { x = Math.min(x, m); } } return x == 10 ? -1 : x; } const count = same(); if (count != -1) { return count; } const x = Math.min(...nums1); const y = Math.min(...nums2); returnMath.min(x * 10 + y, y * 10 + x); };
复杂度分析
时间复杂度:O(m + n),其中 m 和 n 分别是数组 nums}_1 和 nums}_2 的长度。