力扣刷题-1.两数之和

66 阅读1分钟

1.两数之和

var twoSum = function(nums, target) {
            let resArr = []
            for(let i = 0;i < nums.length;i++) {
                const  copyArr = JSON.parse(JSON.stringify(nums))
                copyArr.splice(i,1)
                const copyIndex = copyArr.indexOf(target - nums[i])
                if(copyIndex >= 0 ){
                    const elseNumIndex = (copyIndex >= 0) && (i <= copyIndex ? copyIndex + 1 : copyIndex)
                    resArr = [i,elseNumIndex]
                    return resArr
                }
            }
        }

总结:没理清思路就开始写了,并且也没有对比的方案

思路1(优):一次循环,使用HashMap进行记录

Map.get() 中的 key应该用什么,以及什么时候Map.set()

时间复杂度:O(n)
空间复杂度:O(n)

// 理解Map的思路
var twoSum = function(nums, target) {
    const map = new Map();
    for(let i = 0, len = nums.length;i < len;i++) {
        if(map.has(target - nums[i])) {
            return [map.get(target - nums[i]), i];
        }
        map.set(nums[i], i);
    }
    return [];
}

console.log(twoSum([3,3],6))

思路2:双循环,暴力解法

时间复杂度: O(n^2)O(n2)
空间复杂度: O(1)O(1)

var twoSum = function(nums, target) {
	for(let i = 0,len = nums.length;i < len;i++){
    for(let j = i + 1;j < len;j++){
      if(nums[i] + nums[j] === target) return [i,j]
    }
  }
}