LeetCode.4. Median of Two Sorted Arrays
阿新 • • 發佈:2018-12-22
這道題是讓我們在兩個排序的陣列中找出中位數。
先計算出兩個數組合並在一起的話,中位數的index是多少,當然,我們要計算兩個
m2 = (len1 + len2) / 2;
m1 = m2 - 1;
如果陣列總長度為偶數,那麼中位數就是(m1 + m2) / 2
,如果是計數,那麼就是m2
然後我們用一個index從0開始記錄,再用兩個index分別用來記錄陣列1和陣列2的當前位置,找出小一點的值,如果總index等於m1,或者m2,就記錄下這個數值,直到兩個都找到了,就退出迴圈,最後直接返回中位數即可。
這裡我拆了兩個方法出來,因為測試用例會給其中一個數組為空的情況,因此一個數組為空的情況,就單獨處理一下。
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1 != null && nums1.length > 0 && nums2 != null && nums2.length > 0) {
return both(nums1, nums2);
}
if (nums1.length == 0 && nums2.length > 0) {
return one(nums2);
}
if (nums1.length > 0 && nums2.length == 0) {
return one(nums1);
}
return 0;
}
private double one(int[] nums) {
if (nums.length % 2 == 0) {
return (nums[nums.length / 2] + nums[nums.length / 2 - 1]) / 2d;
} else {
return nums[nums.length / 2];
}
}
private double both(int[] nums1, int[] nums2) {
int currentIndex = 0;
int i = 0;
int j = 0;
boolean foundM1 = false;
boolean foundM2 = false;
int m1 = 0;
int m2 = 0;
int m1Index = 0;
int m2Index = 0;
m2Index = (nums1.length + nums2.length) / 2;
m1Index = m2Index - 1;
if (m1Index < 0) {
m1Index = m2Index;
}
while (!foundM1 || !foundM2) {
int smallOne = 0;
if (i >= nums1.length) {
smallOne = nums2[j];
j++;
} else if (j >= nums2.length) {
smallOne = nums1[i];
i++;
} else {
if (nums1[i] < nums2[j]) {
smallOne = nums1[i];
i++;
} else {
smallOne = nums2[j];
j++;
}
}
if (currentIndex == m1Index) {
foundM1 = true;
m1 = smallOne;
} else if (currentIndex == m2Index) {
foundM2 = true;
m2 = smallOne;
}
currentIndex++;
}
if ((nums1.length + nums2.length) % 2 == 0) {
return (m1 + m2) / 2d;
} else {
return m2;
}
}
}