日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java 两个等长数组的中位数_查询两个数组的中位数

發布時間:2025/4/5 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 两个等长数组的中位数_查询两个数组的中位数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

查詢兩個數組的中位數

Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]

nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]

nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

思路

給定nums1給nums2,則中位數的位置一定能確定,len(nums1) + len(nums2) / 2的取整值,記為median_idx

需要區分是len(nums1) + len(nums2)是奇數還是偶數

兩個指針,只需要從nums1和nums2頭部開始往后移動,將兩者中較小值放入新的數組

當新的數組的長度達到了median_idx,即可求中位數

過程中需要注意兩個數組長度不等的情況,防止下標越界

代碼

class Solution(object):

def findMedianSortedArrays(self, nums1, nums2):

"""

:type nums1: List[int]

:type nums2: List[int]

:rtype: float

"""

median_idx = int((len(nums1) + len(nums2)) / 2)

index1, index2 = 0, len(nums1)

combine_list = nums1 + nums2

new_list = []

i = 0

while i <= median_idx:

if index1 < len(nums1) and index2 - len(nums1) < len(nums2):

new_list.append(min(combine_list[index1], combine_list[index2]))

if combine_list[index1] < combine_list[index2]:

index1 += 1

else:

index2 += 1

elif index1 >= len(nums1):

# nums1 is out of range, append nums2

new_list.append(combine_list[index2])

index2 += 1

elif index2 >= len(nums2):

# nums2 is out of range, append nums1

new_list.append(combine_list[index1])

index1 += 1

i += 1

if (len(nums1) + len(nums2)) % 2 == 0:

median = float(new_list[median_idx] + new_list[median_idx - 1]) / 2

else:

median = new_list[median_idx]

return median

本題以及其它leetcode題目代碼github地址: github地址

總結

以上是生活随笔為你收集整理的java 两个等长数组的中位数_查询两个数组的中位数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。