• 给一个数组和一个值 找出索引之和为这个值的元素组合 找出索引之和为这个值的所有元素组合


    // 给一个数组和一个值,获取数组元素之和为这个值的组合
    function getIndex(arr,v){
        if(!Array.isArray(arr)){
            throw 'TypeError'
        }
        const map = arr.reduce((total, cur, index) => Object.assign(total, { [cur]: index }), {})
        for (let i = 0; i < arr.length; i++) {
            const lack = v - arr[i]
            const rIndex = map[lack]
            if (rIndex !== undefined && rIndex !== i ) {
                return [rIndex, i]
            }
        }
    }
    
    // 给一个数组和一个值,获取数组元素之和为这个值的所有组合
    function getAllIndex(arr, v) {
        if(!Array.isArray(arr)){
            throw 'TypeError'
        }
        const map = arr.reduce((total, cur, index) => Object.assign(total, { [cur]: index }), {})
        const cache = {}
        for (let i = 0; i < arr.length; i++) {
            const lack = v - arr[i]
            const rIndex = map[lack]
            if (rIndex !== undefined && rIndex !== i && !cache[i]) {
                cache[rIndex] = [rIndex, i]
                cache[i] = 1
            }
        }
        return Object.values(cache).filter(Array.isArray)
    }
    console.log(getIndex([2, 2, 1, 3, 5], 4));
    console.log(getAllIndex([2, 2, 1, 3, 5], 4));
    
    
  • 相关阅读:
    Java 老兵不死,Kotlin 蓄势待发
    程序员写代码时戴着耳机,在听什么?
    推荐 7 个提升前端编程效率的 VSCode 插件
    去掉烦人的 !=null
    透析!软件开发未来 10 年的 8 个趋势
    10月01日总结
    09月29日总结
    09月28日总结
    09月27日总结
    09月26日总结
  • 原文地址:https://www.cnblogs.com/ltfxy/p/16420690.html
Copyright © 2020-2023  润新知