Last active
August 12, 2022 16:20
-
-
Save Husseinhj/f168e13b507d72db3e621d96ddaf9883 to your computer and use it in GitHub Desktop.
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.kotlinlang.play | |
fun main() { | |
val num1 = intArrayOf(1,2) | |
val num2 = intArrayOf(3,4) | |
println(findMedianSortedArrays(num1, num2)) | |
} | |
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { | |
val mergedArray = nums1.toMutableList() | |
mergedArray.addAll(nums2.toList()) | |
val sortedMergeNum = mergedArray.sorted() | |
val center: Int = sortedMergeNum.size / 2 | |
val result = if (sortedMergeNum.size % 2 == 0) { | |
((sortedMergeNum[center - 1] + sortedMergeNum[center]).toDouble() / 2) | |
} else { | |
sortedMergeNum[center].toDouble() | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Playground:
https://pl.kotl.in/r04Ilo6hT
LeetCode:
https://leetcode.com/problems/median-of-two-sorted-arrays/