leetcode-4. Median of Two Sorted Arrays-索引值超出范围

def findMedianSortedArrays(self, nums1, nums2):
    """
    :type nums1: List[int]
    :type nums2: List[int]
    :rtype: float
    """
    a = len(nums1)
    b = len(nums2)
    n = a + b
    out = []
    i = 0
    j = 0
    while i < a and j < b:
        if nums1[i] > nums2[j]:
            out.append(nums2[j]) 
            j += 1
        else:
            out.append(nums1[i])
            i += 1
    if n>1 :
        if n%2 == 0:
            return (out[int(n/2)]+out[int((n/2)-1)])/2
        else:
            return out[int(n/2)]
    else:
        return []

有几个样例return (out[int(n/2)]+out[int((n/2)-1)])/2 显示错误因为,索引值超出范围,为什么呀

while i < a and j < b:
    if nums1[i] > nums2[j]:

改成

while i < a or j < b:
    if i>=a or j<b and nums1[i] > nums2[j]:

你题目的解答代码如下:

def findMedianSortedArrays(self, nums1, nums2):
    """
    :type nums1: List[int]
    :type nums2: List[int]
    :rtype: float
    """
    a = len(nums1)
    b = len(nums2)
    n = a + b
    out = []
    i = 0
    j = 0
    while i < a or j < b:
        if i>=a or j<b and nums1[i] > nums2[j]:
            out.append(nums2[j])
            j += 1
        else:
            out.append(nums1[i])
            i += 1
    if n>1 :
        if n%2 == 0:
            return (out[int(n/2)]+out[int((n/2)-1)])/2
        else:
            return out[int(n/2)]
    else:
        return []

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img