题解 | #牛的体重排序#
牛的体重排序
https://www.nowcoder.com/practice/1afd5afef2aa49a8a39b63bb9d2821f9
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param weightsA int整型一维数组
* @param weightsB int整型一维数组
* @return double浮点型
*/
public double findMedianSortedArrays (int[] weightsA, int[] weightsB) {
// write code here
int[] c = new int[weightsA.length + weightsB.length];
int i = 0, j = 0, k = 0;
int m = weightsA.length, n = weightsB.length;
while (i < m && j < n) {
if (weightsA[i] < weightsB[j]) {
c[k++] = weightsA[i++];
} else {
c[k++] = weightsB[j++];
}
}
while (i < m) {
c[k++] = weightsA[i++];
}
while (j < n) {
c[k++] = weightsB[j++];
}
return (m + n) % 2 != 0 ? c[(m + n) / 2] : (c[(m + n) / 2 - 1] + c[(m + n) / 2])
/ 2;
}
}
本题知识点分析:
1.二分查找
2.双指针
3.数学模拟
4.数组遍历和赋值
本题解题思路分析:
1.当A和B都有元素时,将小的值添加到数组c,并且更换索引
2.如果A还有剩余元素,直接添加到C,B同理
3.返回数组C的中位数,如果是奇数,刚好是返回中间位置,如果是偶数,那么取平均值



