美文网首页
LeetCode --4. Median of Two Sort

LeetCode --4. Median of Two Sort

作者: 姜小姜小 | 来源:发表于2019-02-28 08:57 被阅读0次

    陆陆续续在LeetCode上刷了一些题,一直没有记录过,准备集中整理记录一下

    class Solution {
        public double findMedianSortedArrays(int[] A, int[] B) {
            if ((A == null || A.length == 0) && (B == null || B.length == 0)) {
                return -1.0;
            }
            int lenA = (A == null)?0:A.length;
            int lenB = (B == null)?0:B.length;
            int len = lenA + lenB;
            int indexA = 0, indexB = 0, indexC = 0;
            int[] C = new int[len];
            //both A and B have elements
            while (indexA < lenA && indexB < lenB) {
                if (A[indexA] < B[indexB]) {
                    C[indexC++] = A[indexA++];
                } else {
                    C[indexC++] = B[indexB++];
                }
            }
            // only A has elements
            while (indexA < lenA) {
                C[indexC++] = A[indexA++];
            }
            //only B has elements
            while (indexB < lenB) {
                C[indexC++] = B[indexB++];
            }
            int indexM1 = (len - 1) / 2;
            int indexM2 = len / 2;
            if (len % 2 == 0) {
                return (C[indexM1] + C[indexM2]) / 2.0;
            } else {
            return C[indexM2];
            }
        }
    }

    相关文章

      网友评论

          本文标题:LeetCode --4. Median of Two Sort

          本文链接:https://www.haomeiwen.com/subject/htbcuqtx.html