欢迎访问我的博客,目前从事Machine Learning,欢迎交流

【JavaScript】网传字节跳动面试题:请实现数组两数求和

从给定的无序、不重复的数组A中,取出2个数,使其相加和为M。
输出该数组内所有满足上述条件的解的个数。

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text" id="input1" />
    <input type="text" id="input2" />
    <input type="text" id="input3" />
    <span id="show"></span>
    <button onclick="calcu()">计算</button>
    <script>

        function calcu() {
            // 请完成具体实现
            var length = document.getElementById("input1").value;
            var sum = document.getElementById("input2").value;
            var arr = document.getElementById("input3").value.split(",");

            if (length) {
                length = parseInt(length, 10);
            }
            if (sum) {
                sum = parseInt(sum, 10);
            }

            if (arr) {
                arr = arr.map(t => parseInt(t));
            }

            var count = 0;
            var index = 0;
            arr.map((t, i) => {
                if (t <= sum) {
                    var _result = arr.filter((t2, i2) => {
                        return i2 > i && (t2 + t === sum);
                    })
                    console.log(_result)
                    count = count + _result.length
                }
            })


            console.log("符合条件的结果是:" + count);
            document.getElementById("show").innerText = count;
            return 0;
        }

    </script>

</body>

</html>

 

posted @ 2022-04-24 22:43  有蚊子  阅读(88)  评论(0编辑  收藏  举报