Kotlin实现LeetCode算法题之Median of Two Sorted Arrays

题目Median of Two Sorted Arrays(难度Hard

 

Kotlin实现LeetCode算法题之Median of Two Sorted Arrays

 

方案1,数组合并&排序调用Java方法

1 import java.util.* 2 3 class Solution { 4 fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { 5 val lenNums1 = nums1.size 6 val lenNums2 = nums2.size 7 8 val array = Arrays.copyOf(nums1, lenNums1 + lenNums2) 9 System.arraycopy(nums2, 0, array, lenNums1, lenNums2) 10 11 Arrays.sort(array) 12 13 var median: Double 14 val lenArray = array.size 15 if (lenArray % 2 == 1) { 16 median = array[(lenArray - 1) / 2].toDouble() 17 } else { 18 median = (array[(lenArray - 1) / 2] + array[lenArray / 2]).toDouble() / 2 19 } 20 21 return median 22 } 23 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwywzg.html