median of two sorted arrays

后端 未结 10 615
南旧
南旧 2020-12-16 19:12

My question is with reference to Method 2 of this link. Here two equal length sorted arrays are given and we have to find the median of the two arrays merged.



        
相关标签:
10条回答
  • 2020-12-16 19:59

    Because of the equal length constraint, when we compare the two medians, we can safely discard values.

    If m2 is larger than m1, we know that array two must contain a larger quantity of larger values than array one, and therefore all of the small values below m1 are not interesting as long as we discard an equal number of large values from array 2. The result will be a shorter array but the median we are looking for hasn't changed since we've trimmed equally from both sides.

    It sort of reminds me of finding the center of mass of an object by supporting it with your hands far apart and then bringing them slowly together, keeping the object balanced.

    0 讨论(0)
  • 2020-12-16 20:00
     Here is a very simple solution. 
     Actually it need to merger two sorted array and then find the middle.
    
            import java.util.Arrays;
    
    
            public class MedianofTwoArray {
    
                /**
                 * @param args
                 */
                public static void main(String[] args) {
    
                    int []array1= {1,2,3,4,5};
                    int []array2= {6,7,8,9,10};
                    int median;
                    median=findMedian(array1,array2);
                    System.out.println(median);
    
                }
    
                public static int findMedian(int []arr1,int []arr2) {       
                    int [] tempArr=new int[arr1.length+arr2.length]; //creating an array of the length ,equals to sum of arr1 and arr2
                    int i=0;
                    int j=0;
                    int k=0;
    
                    while(i<arr1.length&&j<arr2.length) { /*comparing elements of the two arrays and copying the smaller one into tempArr and
                     incrementing the index of the array from which value is copied */
                        if(arr1[i]<=arr2[j]) {
                            tempArr[k]=arr1[i];
    
                            i++;
                        }else {
                            tempArr[k]=arr2[j];
    
                            j++;
                        }
                        k++;
                    }
                    //copying the left over elements from both arrays
                    if(i==arr1.length) {
                        while(j<arr2.length) {
                        tempArr[k]=arr2[j];
                        j++;
                        k++;
                        }
                    }else {
                        while(i<arr1.length) {
                            tempArr[k]=arr2[j];
                            j++;
                            k++;
                            }
    
                    }
                    System.out.println(Arrays.toString(tempArr));
                    return tempArr[tempArr.length/2];
                }
    
            }
    
    0 讨论(0)
  • 2020-12-16 20:01

    Javascript solution to finding median of two sorted arrays:

    const findMedian = (arr1, arr2) => {
      const len = arr1.length + arr2.length;
      return len % 2 ? oddMedian(Math.floor(len/2), arr1, arr2) : evenMedian((len/2)-1, len/2, arr1, arr2);
    }
    
    const oddMedian = (medianIndex, arr1, arr2) => {
      if (arr1[arr1.length-1] < arr2[0]) {
        if (arr1.length > medianIndex) {
          return arr1[medianIndex];
        } else if (arr1.length <= medianIndex) {
          return arr2[medianIndex - arr1.length];
        }
      } else if (arr2[arr2.length-1] < arr1[0]) {
        if (arr2.length > medianIndex) {
          return arr2[medianIndex];
        } else if (arr2.length <= medianIndex) {
          return arr1[medianIndex - arr2.length];
        }
      } else {
        const [shorterArr, largerArr] = arr1.length < arr2.length ? [arr1, arr2] : [arr2, arr1];
        let j = 0;
        let k = 0;
        const sortedArr = [];
        for (let i = 0; i <= medianIndex; i++) {
          if (shorterArr[j] <= largerArr[k]) {
            sortedArr[i] = shorterArr[j];
            j++;
          } else {
            sortedArr[i] = largerArr[k];
            k++;
          }
        }
        return sortedArr[medianIndex];
      }
    }
    
    const evenMedian = (medianIndex1, medianIndex2, arr1, arr2) => {
      if (arr1[arr1.length-1] < arr2[0]) {
        if (arr1.length-1 >= medianIndex2) {
          return (arr1[medianIndex1]+arr1[medianIndex2])/2;
        } else if (arr1.length-1 < medianIndex1) {
          const firstMedianIndex = medianIndex1 - arr1.length;
          return (arr2[firstMedianIndex]+arr2[firstMedianIndex+1])/2;
        } else {
          return (arr1[arr1.length-1] + arr2[0])/2;
        }
      } else if (arr2[arr2.length-1] < arr1[0]) {
        if (arr2.length-1 >= medianIndex2) {
          return (arr2[medianIndex1]+arr2[medianIndex2])/2;
        } else if (arr2.length-1 < medianIndex1) {
          const firstMedianIndex = medianIndex1 - arr2.length;
          return (arr1[firstMedianIndex]+arr1[firstMedianIndex+1])/2;
        } else {
          return (arr2[arr2.length-1] + arr1[0])/2;
        }
      } else {
        const [shorterArr, largerArr] = arr1.length < arr2.length ? [arr1, arr2] : [arr2, arr1];
        let i = 0;
        let j = 0;
        let k = 0;
        const sortedArr = [];
        for (let i = 0; i <= medianIndex2; i++) {
          if (shorterArr[j] <= largerArr[k]) {
            sortedArr.push(shorterArr[j]);
            j++;
          } else {
            sortedArr.push(largerArr[k]);
            k++;
          }
        }
        return (sortedArr[medianIndex1] + sortedArr[medianIndex2])/2;
      }
    }
    

    Example

    console.log("Result:", findMedian([1,3,5], [2,4,6,8]));
    console.log("Result:", findMedian([1,3,5,7,10], [2,4,6,8]));
    console.log("Result:", findMedian([1,3,5,7,10], [2,4,6,8,9]));
    console.log("Result:", findMedian([1,3,5], [2,4,6,8,9]));
    console.log("Result:", findMedian([1,3,5,7], [2,4,6,8,9,10]));
    console.log("Result:", findMedian([1,3,5,7,10], [2,4,6]));
    console.log("Result:", findMedian([1,3,5,7], [2,4]));
    console.log("Result:", findMedian([1,2,4], [3,5,6,7,8,9,10,11]));
    console.log("Result:", findMedian([1], [2, 3, 4]));
    console.log("Result:", findMedian([1, 2], [3, 4]));
    console.log("Result:", findMedian([1], [2, 3]));
    

    Output

    Result: 4
    Result: 5
    Result: 5.5
    Result: 4.5
    Result: 5.5
    Result: 4.5
    Result: 3.5
    Result: 6
    Result: 2.5
    Result: 2.5
    Result: 2
    
    0 讨论(0)
  • 2020-12-16 20:04

    This is my C# solution:

    public double FindMedianSortedArrays(int[] nums1, int[] nums2) {

        List<int> sorted = new List<int>();
    
        if(nums1.Length>nums2.Length){
            for(int i=0; i<nums1.Length; i++){
    
                sorted.Add(nums1[i]);
    
                if(i<nums2.Length)
                    sorted.Add(nums2[i]);
            }
        }
        else{
            for(int i=0; i<nums2.Length; i++){
    
                sorted.Add(nums2[i]);
    
                if(i<nums1.Length)
                    sorted.Add(nums1[i]);
            }
        }
    
        sorted.Sort();
    
        if(sorted.Count % 2 !=0)
           return (double)sorted[sorted.Count/2];
    
           return (double)(sorted[sorted.Count/2-1]+ sorted[sorted.Count/2])/2;
    }
    
    0 讨论(0)
提交回复
热议问题