LeetCode Median of Two Sorted Arrays Binary Search (golang)

Problem
在这里插入图片描述
Analysis Process

The problem says there are two arrays and the overall run time complexity should be O(log(m+n)),it’s natural to think about merging arrays and binary search.

By the definition of median, when m+n is odd,the median is the (m+n)/2 element in two ordered arrays.when m+n is even,median is the (m+n)/2 and (m+n)/2+1 element in two ordered arrays
So, this problem translates to looking for the k smallest number in two ordered arrays

Suppose the two ordered arrays are A and B
1.If A[k/2−1]<B[k/2−1],the only numbers that are less than A[k/2−1] are the first k/2−1 of A and the first k/2−1 of B.So,A[k/2−1] can’t be the k element,rule out A[0] to A[k/2−1]
2.If A[k/2−1]>B[k/2−1],rule out B[0] to B[k/2−1]
3.If A[k/2−1]=B[k/2−1],same as the first case

Consider the following special cases
1.f A[k/2−1] or B[k/2−1] cross the line ,pick the last element in the corresponding array
2. If an array is empty, all elements in the array are excluded, and we can simply return the k smallest element in another array
3. If k=1, we just return the minimum value of the first element of both arrays

Code

func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
	Length := len(nums1) + len(nums2)    // Calculate the total length of the array
	if Length % 2 == 1 {
		return float64(getKthElement(nums1, nums2, totalLen / 2 + 1))  // Dentermin whether it's odd or even
	}
	return float64(getKthElement(nums1, nums2, totalLen / 2) + getKthElement(nums1, nums2, totalLen / 2 + 1)) / 2.0
}

func getKthElement(nums1 []int, nums2 []int, k int) int {
	index1, index2 := 0, 0
	for {
		// Determine whether the loop has completed
		if index1 == len(nums1) {
			return nums2[index2 + k - 1]
		}                           // take the middle value of nums2
		if index2 == len(nums2) {
			return nums1[index1 + k - 1]
		}
		if k == 1{
			return min(nums1[index1], nums2[index2])  //the length of nums1 equals nums2
		}      //Returns the smallest first element in both arrays,because the purpose of getKthElement is to find the k smallest element

		half := k / 2
		// Determine whether cross the line
		newIndex1 := min(index1 + half, len(nums1)) - 1
		newIndex2 := min(index2 + half, len(nums2)) - 1

		pivot1, pivot2 := nums1[newIndex1], nums2[newIndex2]
		if pivot1<= pivot2 {
			k -= (newIndex1 - index1) + 1
			index1 = newIndex1 + 1
		} else {
			k -= (newIndex2 - index2) + 1
			index2 = newIndex2 + 1
		}
 	}
	return 0
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

猜你喜欢

转载自blog.csdn.net/qq_46595591/article/details/107530641
今日推荐