0

Why subtracr one from median. Python binary search example

Hello folks. I'm solving leetcode question related to binary search everything went smoothly. Until the last line where arr[len(arr)//2-1 I'm trying to access the median of an even array. Why tho subtracted instead of the regular law of median Median = number at the middle + add one to get th3 number after/2 class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ arr = nums1 + nums2 arr.sort() if len(arr) % 2 != 0: return arr[len(arr)//2] else: return (arr[len(arr)//2] + arr[len(arr)//2-1])*1.00/2 Here's the link of the question ineetcoze https://leetcode.com/problems/median-of-two-sorted-arrays/description/ Any tips?

8th Oct 2022, 1:36 PM
Fatimah Mohammad Emad EL Den
1 Odpowiedź
+ 2
The "regular law of median" https://en.m.wikipedia.org/wiki/Median If the number of elements is odd, the median is the element at the center. _ _ X _ _ Example: len(arr)=5 then median is the 3rd element, which in Python is arr[2] The integer division // works here because it rounds down. If the number of elements is even, the median is the average of the two central elements. _ _ X|X _ _ Example: len(arr)=6 then the elements at the center are the 3rd and 4th element, with index of 2 and 3. If we do the math, 6//2=3 so this is the higher index, the other element is at the previous index. So we take the average of arr[len(arr)//2] and arr[len(arr)//2-1] The same is expressed in the code.
8th Oct 2022, 2:37 PM
Tibor Santa
Tibor Santa - avatar