题目
题目链接:
https://www.nowcoder.com/practice/b3b59248e61f499482eaba636305474b
思路
直接模拟2个数组有顺序放到一个数组中help中如果help长度为奇数,返回中间的数如果help长度为偶数,返回中间2个数的和除以2
参考答案java
import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param nums1 int整型ArrayList* @param nums2 int整型ArrayList* @return double浮点型*/public double Median (ArrayList<Integer> nums1, ArrayList<Integer> nums2) {int n = nums1.size();int m = nums2.size();int len = n + m;int[] help = new int[len];int x = n - 1;int y = m - 1;int z = len - 1;while (x >= 0 && y >= 0) {if (nums1.get(x) > nums2.get(y)) {help[z--] = nums1.get(x--);} else {help[z--] = nums2.get(y--);}}while (x >= 0) {help[z--] = nums1.get(x--);}while (y >= 0) {help[z--] = nums2.get(y--);}if (len % 2 == 1) {int i1 = (len - 1) / 2;return (double) help[i1];} else {int i1 = (len - 1) / 2;int i2 = i1 + 1;return ((double) help[i1] + (double) help[i2]) / 2;}}
}
参考答案Go
package main/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param nums1 int整型一维数组* @param nums2 int整型一维数组* @return double浮点型*/
func Median(nums1 []int, nums2 []int) float64 {n := len(nums1)m := len(nums2)length := n + mhelp := make([]float64, length)x := n - 1y := m - 1z := length - 1for x >= 0 && y >= 0 {if nums1[x] >= nums2[y] {help[z] = float64(nums1[x])z--x--} else {help[z] = float64(nums2[y])z--y--}}for x >= 0 {help[z] = float64(nums1[x])z--x--}for y >= 0 {help[z] = float64(nums2[y])z--y--}if length%2 == 1 {return help[(length-1)/2]} else {i1 := (length - 1) / 2i2 := i1 + 1return (help[i1] + help[i2]) / 2}
}
参考答案PHP
<?php/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param nums1 int整型一维数组* @param nums2 int整型一维数组* @return double浮点型*/
function Median( $nums1 , $nums2 )
{$n = count($nums1);$m= count($nums2);$len = $n+$m;$help = array();$x = $n-1;$y = $m-1;$z = $len-1;while ($x >=0 && $y>=0){if($nums1[$x] >$nums2[$y]){$help[$z--] = $nums1[$x--];}else{$help[$z--] = $nums2[$y--];}}while ($x>=0){$help[$z--]= $nums1[$x--];}while ($y>=0){$help[$z--] = $nums2[$y--];}if($len%2 ==1){return $help[intval(($len-1)/2)];}else{$i1 = intval(($len-1)/2);$i2 =$i1+1;return ($help[$i1]+$help[$i2])/2;}
}