add leetcod4

dev
ehlxr 2020-09-27 23:31:14 +08:00
parent 6c8399a9ba
commit fc939a2ad1
1 changed files with 102 additions and 0 deletions

View File

@ -0,0 +1,102 @@
package me.ehlxr.leetcode;
/**
* 4.
*
* @author ehlxr
* @since 2020-09-27 21:12.
*/
public class Solution4 {
/**
*
*
*/
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] result = new int[nums1.length + nums2.length];
int x = 0, y = 0, z = 0;
while (x < nums1.length || y < nums2.length) {
if (x >= nums1.length) {
result[z] = nums2[y];
y++;
z++;
continue;
}
if (y >= nums2.length) {
result[z] = nums1[x];
x++;
z++;
continue;
}
if (nums1[x] < nums2[y]) {
result[z] = nums1[x];
x++;
} else {
result[z] = nums2[y];
y++;
}
z++;
}
int m = result.length / 2;
if (result.length % 2 == 0) {
return (result[m] + result[m - 1]) / 2.0;
} else {
return result[m];
}
}
/**
* len
* len+1/2 int(len/2 ) + 1
* len/2 len/2+1 len/2+1
*
* len/2+1
*
* https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-2/
*/
public static double findMedianSortedArrays2(int[] nums1, int[] nums2) {
int l1 = nums1.length, l2 = nums2.length,
left = 0, right = 0,
len = l1 + l2,
x = 0, y = 0;
for (int i = 0; i < len/2 +1; i++) {
left = right;
if (x >= nums1.length) {
right = nums2[y];
y++;
continue;
}
if (y >= nums2.length) {
right = nums1[x];
x++;
continue;
}
if (nums1[x] < nums2[y]) {
right = nums1[x];
x++;
} else {
right = nums2[y];
y++;
}
}
if (len % 2 == 0) {
return (left + right) / 2.0;
} else {
return right;
}
}
public static void main(String[] args) {
System.out.println(findMedianSortedArrays(new int[]{}, new int[]{2, 3}));
System.out.println(findMedianSortedArrays2(new int[]{1, 4}, new int[]{2, 3}));
System.out.println(findMedianSortedArrays2(new int[]{3}, new int[]{1, 4, 6}));
}
}