题解 | #牛的体重排序#
牛的体重排序
https://www.nowcoder.com/practice/1afd5afef2aa49a8a39b63bb9d2821f9
考察数组合并。根据题意创建足够长的数组,直接利用双指针进行一次遍历,没遍历完的补在后面就可以了。
完整Java代码如下所示
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;
//a,b数组都有元素时
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;
}
}
联想公司福利 1481人发布
查看6道真题和解析