【leetcode阿里题库】4. Median of Two Sorted Arrays
程序员文章站
2022-07-15 10:46:55
...
解题思路
双指针。
提交代码
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1=nums1.length,len2=nums2.length;
int p1=(len1+len2-1)/2;
int p2=(len1+len2)/2;
int num1=findNth(nums1,nums2,p1);
int num2=findNth(nums1,nums2,p2);
return (double)(num1+num2)/2;
}
public int findNth(int[] nums1, int[] nums2, int pos){
int len1=nums1.length,len2=nums2.length;
int p1=0,p2=0;
while((p1+p2)<pos) {
if(p1==len1) p2++;
else if(p2==len2) p1++;
else {
if(nums1[p1]<nums2[p2])
p1++;
else
p2++;
}
}
if(p1==len1) return nums2[p2];
else if(p2==len2) return nums1[p1];
else return nums1[p1]<nums2[p2]?nums1[p1]:nums2[p2];
}
}
运行结果
推荐阅读
-
【LeetCode】4. Median of Two Sorted Arrays
-
LeetCode 4. 两个排序数组的中位数 Median of Two Sorted Arrays
-
LeetCode算法系列:4、Median of Two Sorted Arrays
-
4. Median of Two Sorted Arrays
-
4. Median of Two Sorted Arrays
-
【leetcode】4. Median of Two Sorted Arrays
-
【leetcode阿里题库】4. Median of Two Sorted Arrays
-
LeetCode 4. Median of Two Sorted Arrays
-
从0开始的leetCode:Median of Two Sorted Arrays
-
【Leetcode 4】Median of Two Sorted Arrays