4.寻找两个有序数组的中位数

JavaScript

战胜87.91%的JavaScript提交

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var findMedianSortedArrays = function(nums1, nums2) {
let arr = nums1.concat(nums2);
arr.sort((x, y) => {
if (x < y) {
return -1;
} else {
return 1;
}
return 0;
})
let len = arr.length;
if ((len - 1) % 2 == 0) {
let index = (len - 1) / 2;
return Number(arr[index]);
} else {
let index = parseInt((len - 1) / 2)
let result = ((arr[index] + arr[index + 1]) / 2).toFixed(1)
return Number(result);
}
};

Java

战胜52.46%的Java提交

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1 = nums1.length, len2 = nums2.length;
int[] arr = new int[nums1.length + nums2.length];
for (int i = 0; i < len1; i++) {
arr[i] = nums1[i];
}
int index = len1;
for (int i = 0; i < len2; i++) {
arr[index++] = nums2[i];
}
Arrays.sort(arr);
if ((arr.length - 1) % 2 == 0) {
return arr[(arr.length - 1) / 2];
} else {
int flag = (arr.length - 1) / 2;
return ((double)arr[flag] + (double)arr[flag + 1]) / 2;
}
}
}