2540. Minimum Common Value

Difficulty:
Related Topics:
Similar Questions:

Problem

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.

  Example 1:

Input: nums1 = [1,2,3], nums2 = [2,4]
Output: 2
Explanation: The smallest element common to both arrays is 2, so we return 2.

Example 2:

Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5]
Output: 2
Explanation: There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.

  Constraints:

Solution (Java)

class Solution {
    public int getCommon(int[] nums1, int[] nums2) {
        Set<Integer> treeset1 = new TreeSet<>();
        Set<Integer> treeset2 = new TreeSet<>();
        //Put the numbers in the sets
        for(int num : nums1){
            treeset1.add(num);
        }

        for(int num : nums2){
            treeset2.add(num);
        }
        //iterate any set and if we find the same number in the other set, we return that
        //Here since it is a treeset, we are starting from the smallest number itself.
        for(Integer num : treeset1){
            if(treeset2.contains(num)){
                return num;
            }
        }

        return -1;
    }
}

Explain:

nope.

Complexity: