leetcode-4. Encuentra la mediana de dos matrices positivas

Asunto: https://leetcode-cn.com/problems/median-of-two-sorted-arrays/

responder:

1. Combinar y ordenar matrices

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

 int [] nums3 = new int [nums1.length + nums2.length];

           int i = 0, j = 0, k = 0;

           while (i <nums1.length && j <nums2.length) {

               if (nums1 [i] <nums2 [j]) {

                   nums3 [k ++] = nums1 [i ++];

               }más{

                   nums3 [k ++] = nums2 [j ++];

               }

           }

           while (i <nums1.length) {

               nums3 [k ++] = nums1 [i ++];

           }

           while (j <nums2.length) {

               nums3 [k ++] = nums2 [j ++];

           }

           if (nums3.length% 2 == 0) {

               return ((doble) nums3 [nums3.length / 2-1] + (doble) nums3 [nums3.length / 2]) / 2;

           }más{

               return nums3 [nums3.length / 2];

           }

    }

La complejidad temporal es O (m + n) y la complejidad espacial O (m + n) no cumple los requisitos

2. Aquí obtiene la matriz ordenada completa. De hecho, no necesita saber todo, solo necesita conocer la mediana.

Si m + n es un número par, obtenemos (m + n) / 2 números y (m + n) / 2 + 1 números, es decir, las coordenadas son (m + n) / 2 -1 y (m + n) / 2

Si m + n es un número impar, obtenemos (m + n + 1) / 2 números, es decir, las coordenadas son (m + n + 1) / 2-1.

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

  int m = nums1.length;

          int n = nums2.length;

          int longitud = m + n;

          int izquierda = -1, derecha = -1;

          int inicio1 = 0, inicio2 = 0;

          para (int i = 0; i <= longitud / 2; i ++) {

              izquierda = derecha;

              if (inicio1 <m && (inicio2> = n || nums1 [inicio1] <nums2 [inicio2])) {

                  right = nums1 [inicio1 ++];

              }más{

                  right = nums2 [inicio2 ++];

              }

          }

          if ((longitud & 1) == 0) return (izquierda + derecha) /2.0;

          volver a la derecha;

    }

La complejidad temporal de la pregunta sigue siendo O (m + n), y la complejidad del control es O (1)

3. Versión avanzada de la solución 2, encuentre el k-ésimo decimal, búsqueda binaria de variantes de pensamiento

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

  int longitud1 = nums1.length;

         int length2 = nums2.length;

         int left = (length1 + length2 + 1) / 2;

         int right = (length1 + length2 + 2) / 2;

// Si length1 + length2 son números impares, la izquierda y la derecha son iguales y los números pares no son iguales

         return (getK (nums1,0, length1-1, nums2,0, length2-1, left) +

                 getK (nums1,0, length1-1, nums2,0, length2-1, right)) / 2.0;

    }

    public int getK (int [] nums1, int start1, int end1, int [] nums2, int start2, int end2, int k) {

        int len1 = end1-start1 + 1;

        int len2 = end2-start2 + 1;

        if (len1> len2) return getK (nums2, start2, end2, nums1, start1, end1, k);

        if (len1 == 0) return nums2 [inicio2 + k-1];

        if (k == 1) return Math.min (nums1 [inicio1], nums2 [inicio2]);

        int index1 = start1 + Math.min (len1, k / 2) -1;

        int index2 = start2 + Math.min (len2, k / 2) -1;

        if (nums1 [index1]> nums2 [index2]) {

            return getK (nums1, start1, end1, nums2, index2 + 1, end2, k- (index2-start2 + 1));

        }más{

            return getK (nums1, index1 + 1, end1, nums2, start2, end2, k- (index1-start1 + 1));

        }

    }

La complejidad del tiempo es O (log (m + n)) y la complejidad del control es) O (1)

4. Búsqueda binaria:

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

  int m = nums1.length;

        int n = nums2.length;

        si (m> n) {

            return findMedianSortedArrays (nums2, nums1);

        }

        int iMin = 0, iMax = m;

        while (iMin <= iMax) {

            int i = (iMin + iMax) / 2;

            int j = (m + n + 1) / 2 - yo;

            if (j! = 0 && i! = m && nums2 [j-1]> nums1 [i]) {// i 需要 增大

                iMin = i + 1;

            }

            más si (i! = 0 && j! = n && nums1 [i-1]> nums2 [j]) {// i 需要 减小

                iMax = i - 1;

            }

            else {// Cumplir con los requisitos y enumerar las condiciones límite para su consideración por separado

                int maxLeft = 0;

                if (i == 0) {maxLeft = nums2 [j-1]; }

                else if (j == 0) {maxLeft = nums1 [i-1]; }

                else {maxLeft = Math.max (nums1 [i-1], nums2 [j-1]); }

                if ((m + n)% 2 == 1) {return maxLeft;} // Si el número es impar, no hay necesidad de considerar la mitad derecha

 

                int minRight = 0;

                if (i == m) {minRight = nums2 [j]; }

                si no (j == n) {minRight = nums1 [i]; }

                else {minRight = Math.min (nums2 [j], nums1 [i]); }

 

                return (maxLeft + minRight) / 2.0; // Si es un número par, devuelve el resultado

            }

        }

        return 0.0;

    }

La complejidad del tiempo es O (log (min (m, n)) y la complejidad del espacio es O (1)

 

Supongo que te gusta

Origin blog.csdn.net/wuqiqi1992/article/details/108355775
Recomendado
Clasificación