给定两个分别有序的数组nums1,nums2,输出这两个数组总体排序后的第K小的元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  
func findKthElement(nums1, nums2 []int, k int) int {
var getKthElement func([]int, []int, int) int
getKthElement = func(arr1 []int, arr2 []int, k int) int {
l1, l2 := len(arr1), len(arr2)
if l1 > l2 {
return getKthElement(arr2, arr1, k)
}
if l1 == 0 {
return arr2[k-1]
}
if k == 1 {
return min(arr1[0], arr2[0])
}

i := min(l1, k/2)
j := min(l2, k/2)

if arr1[i-1] > arr2[j-1] {
return getKthElement(arr1, arr2[j:], k-j)
} else {
return getKthElement(arr1[i:], arr2, k-i)
}
}

return getKthElement(nums1, nums2, k)
}

func min(a, b int) int {
if a > b {
return b
}
return a
}

func main() {
fmt.Println(findKthElement([]int{2, 4, 6, 8}, []int{1, 3, 5, 7}, 4))
}