Topic describes
Their thinking
- The problem uses the method of double pointer.
- A pointer to array 1.
- A pointer to array 2.
- Compare the size of the elements to which the two Pointers point, adding the smaller one to the sorted array until one of the elements has been iterated, adding the remaining elements to the sorted array.
- And then we decide if we have an odd or even number of elements, and if it’s odd we return the median element, and if it’s even we return the median element and the one after the median element, sum them up and then we return PI over 2.
The problem solving code
var findMedianSortedArrays = function(nums1, nums2) {
// We need to make it clear that both arrays are in positive order
/ / double pointer
let left = 0;
let right = 0;
// define merge array
const mergeArr = [];
// when one of the arrays reaches the end of the loop
while (left < nums1.length && right < nums2.length) {
if (nums1[left] <= nums2[right]) {
mergeArr.push(nums1[left]);
left++;
} else{ mergeArr.push(nums2[right]); right++; }}if(right === nums2.length) { mergeArr.push(... nums1.slice(left)) }if(left === nums1.length) { mergeArr.push(... nums2.slice(right)) }if (mergeArr.length % 2) {
return mergeArr[(mergeArr.length-1) > >1]}else {
return (mergeArr[(mergeArr.length-1) > >1] + mergeArr[((mergeArr.length-1) > >1) + 1) /2}};Copy the code
Conclusion (this topic gives us the enlightenment of thinking)
- Learn how to solve problems using two Pointers.
- Learn to use displacement to find the median.