js 數組中尋找兩個值相加等於目標值, 三個值相加等於目標值


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script type="text/javascript">
    let nums = [1, 5, 2, 4, 6, 8];
    let target = 12;

    function twoNum (nums, target){
        let arr = [];
        for(let i = 0;i < nums.length;i++){
            let otherNum = target - nums[i];
            let secondNum = nums.slice(i+1).filter(val => val == otherNum);
            if(secondNum.length > 0){
                arr.push(i, nums.indexOf(secondNum[0]));
            }
        }
        return arr;
    }
    
    function three(nums, target){
        let resultArr = [];
        for(let i = 0;i < nums.length;i++){
            let otherNum = target - nums[i];
            let arr = twoNum(nums.slice(i+1), otherNum);
            if(arr.length > 0){
                resultArr.push(i, nums.indexOf(nums.slice(i+1)[arr[0]]), nums.indexOf(nums.slice(i+1)[arr[1]]));
                break;
            }
        }
        return resultArr
    }

    three([1, 4, 8, 12, 19, 16, 26], 24);
</script>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM