题目
题目链接:
https://www.nowcoder.com/practice/b6bb0bce88894108bfc23e9b7b012420
思路
模拟,2数组合并一个数组helphelp长度为奇数,直接取中间值,为偶数,中间2个值,哪个小返回哪个
参考答案Java
import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param arr1 int整型一维数组* @param arr2 int整型一维数组* @return int整型*/public int getUpMedian (int[] arr1, int[] arr2) {int n = arr1.length;int m = arr2.length;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 (arr1[x] > arr2[y]) {help[z--] = arr1[x--];} else {help[z--] = arr2[y--];}}while (x >= 0) {help[z--] = arr1[x--];}while (y >= 0) {help[z--] = arr2[y--];}if(len%2 ==1) {return help[(len-1)/2];}else{int i1 = (len-1)/2;int i2 = i1+1;if(help[i1] > help[i2]){return help[i2];}else{return help[i1];}}}
}
参考答案Go
package main/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param arr1 int整型一维数组* @param arr2 int整型一维数组* @return int整型*/
func getUpMedian(arr1 []int, arr2 []int) int {n := len(arr1)m := len(arr2)length := n + mhelp := make([]int, length)x := n - 1y := m - 1z := length - 1for x >= 0 && y >= 0 {if arr1[x] >= arr2[y] {help[z] = arr1[x]z--x--} else {help[z] = arr2[y]z--y--}}for x >= 0 {help[z] = arr1[x]z--x--}for y >= 0 {help[z] = arr2[y]z--y--}if length%2 == 1 {return help[(length-1)/2]} else {i1 := (length - 1) / 2i2 := i1 + 1if help[i1] > help[i2] {return help[i2]} else {return help[i1]}}
}