leetcode update

This commit is contained in:
gameloader 2024-03-09 10:35:21 +08:00
parent d4ba19406c
commit dd940b8a89

View File

@ -749,3 +749,49 @@ func maxFrequencyElements(nums []int) int {
### 总结
本题注意考查数据范围, 在数据范围有限的情况下直接使用数组要比哈希表快得多.
## day12 2024-03-09
### 2540. Minimum Common Value
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.
### 题解
本题使用两个指针分别指向两个数组, 然后依次移动两个指针比较大小即可, 位于数值更小的位置的数组指针向前移动直到相等或者到数组末尾为止.
### 代码
```go
func getCommon(nums1 []int, nums2 []int) int {
index1, index2 := 0 , 0
for index1<len(nums1) && index2 < len(nums2){
if nums1[index1] < nums2[index2]{
index1++
}else if nums2[index2] < nums1[index1]{
index2++
} else{
return nums1[index1]
}
}
return -1
}
```
### 总结
这是一道典型的双指针问题, 思路清晰就可以很快解决.