budd/src/main/java/io/github/ehlxr/leetcode/Solution4.java

127 lines
4.1 KiB
Java
Raw Normal View History

2020-12-10 03:05:29 +00:00
/*
* The MIT License (MIT)
*
* Copyright © 2020 xrv <xrg@live.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
2020-12-09 09:55:24 +00:00
package io.github.ehlxr.leetcode;
2020-09-27 15:31:14 +00:00
/**
* 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}));
}
}