This is the 19th day of my participation in the August More Text Challenge
preface
Today comes an array related topic, looking for the median in the array, this idea is not difficult, this article is mainly for the front-end developers to a JavaScript version of the solution method, this solution method used in ES6 new features, specific ideas and code as follows
Topic describes
Given two positive-ordered (from small to large) arrays of size m and n, nums1 and nums2. Please find and return the median of the two positive ordinal groups.
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Merge array = [1,2,3], median 2
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Merge array = [1,2,3,4], median (2 + 3) / 2 = 2.5
Example 3:
Input: nums1 = [0,0], nums2 = [0,0]
Output: 0.00000
Example 4:
Input: nums1 = [], nums2 = [1]
Output: 1.00000
Example 5:
Input: nums1 = [2], nums2 = []
Output: 2.00000
Their thinking
- Kinds of input are two arrays, we require two arrays of merger of the median, and is the median to sort good array, because the input is ordinal group, here we can use the merge to obtain merger array, merge the ideas we can see this topic, this article is ordered by directly using the sort of.
- There are two cases where you get the sorted array, if the array is odd, then the median is the length of the array divided by 2, or if the array is even, then the median is the sum of the length of the array divided by 2
- Return the result according to different situations, the code is as follows
/ * * *@param {number[]} nums1
* @param {number[]} nums2
* @return {number}* /
var findMedianSortedArrays = function(nums1, nums2) {
var mergeArr = []
var medianIndex = 0
mergeArr = [...nums1,...nums2].sort((a,b) = > a-b) // Here we use es6 expansion to merge two arrays, and sort by sort to get the combined ordered array
if(mergeArr.length%2= = =1) {// Merge an odd array length
medianIndex = Math.floor(mergeArr.length/2)
return mergeArr[medianIndex]
}else{ // Merge an array into an even number
var median1 = mergeArr.length/2
var median2 = median1-1
return (mergeArr[median1]+mergeArr[median2])/2}};Copy the code
LeetCode run result
conclusion
This is a simple array to take the median of the topic, mainly divided into two cases, to consider clearly, the second is the method of combining the array, can use the ordinary array method concat, can also use es6 expansion operation. That’s about it. If you have any ideas, please point them out in the comments