标签:正序 int 中位数 nums1 ++ length total Leetcode nums2
题目描述
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
解题思路
将两个有序数组归并为一个有序数组,直接获取对应下标的元素即可。
解题代码
// 归并两个数组
public int[] merge(int[] nums1, int[] nums2) {
int[] total = new int[nums1.length + nums2.length];
// i: nums1的索引,j: nums2的索引, k: total的索引
int i = 0, j = 0, k = 0;
// 遍历并比较两个数组的元素并且将较小的元素放入total数组中
while (i < nums1.length && j < nums2.length) {
// 比较大小
if (nums1[i] < nums2[j]) {
total[k++] = nums1[i++];
} else {
total[k++] = nums2[j++];
}
}
// 如果nums1数组还有元素
while (i < nums1.length) {
total[k++] = nums1[i++];
}
// 如果nums2数组还有元素
while (j < nums2.length) {
total[k++] = nums2[j++];
}
return total;
}
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] total = merge(nums1, nums2);
int len = total.length;
if (total.length % 2 == 0) {
return (total[len / 2 - 1] + total[len / 2]) / 2.0;
} else {
return total[len / 2] * 1.0;
}
}
题目来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
标签:正序,int,中位数,nums1,++,length,total,Leetcode,nums2 来源: https://www.cnblogs.com/fenfeng9/p/15092550.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。