[JS做LeetCode] Median of Two Sorted Arrays

Median of Two Sorted Arrays

<html>

<head>
    <meta http-equiv="charset" content="utf-8"></head>

<body>
    <script>
        //解题思路:
        //找出中位数要循环的次数为loop
        //posA为数组A的下标,posB为数组B的下标
        //每次循环找出两个数组对应下标比较小的值,进栈,下标+1
        //注意判断数组为空的情况

        var A = [0,1,4,8];
        var B = [2,7,9,10];
        var findMedianSortedArrays = function(A, B) {
                var m = A.length;
                var n = B.length;
                var loop = Math.floor((m+n)/2)+1;
                var posA = 0;
                var posB = 0;
                var stack = [];

                for(var i=0; i<loop; i++) {
                        if(posA === m) {
                                stack.push(B[posB]);
                                posB++;
                                continue;
                        }
                        if(posB === n) {
                                stack.push(A[posA]);
                                posA++;
                                continue;
                        }
                        if(A[posA]<B[posB]) {
                                stack.push(A[posA]);
                                posA++;
                        } else {
                                stack.push(B[posB]);
                                posB++;
                        }
                }
                if((m+n)%2 === 0) {
                        return (stack.pop()+stack.pop())/2;
                } else {
                        return stack.pop();
                }
        };

        alert(findMedianSortedArrays(A, B));
    </script></body>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。