[LeetCode] Minimum Common Value

2541. Minimum Operations to Make Array Equal II

Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the minimum integer common to both arrays. If there is no common integer amongst nums1 and nums2, return -1.

Note that an integer is said to be common to nums1 and nums2 if both arrays have at least one occurrence of that integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int getCommon(vector<int>& nums1, vector<int>& nums2) {
int i = 0, j = 0;
while(i < nums1.size() and j < nums2.size()) {
if(nums1[i] == nums2[j]) return nums1[i];
else if(nums1[i] < nums2[j]) i++;
else j++;
}
return -1;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/01/21/PS/LeetCode/minimum-common-value/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.