小白js硬啃leetcode算法-两数之和(数组简单-1)-1

102 阅读2分钟

题目

1、给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 你可以按任意顺序返回答案
范例: 输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1]。

暴力解法

  • 解题思路:
    • 最容易想到的就是将数组进行两层循环,分别取出两个数,相加是否与目标值相等。
  • 复杂度
    • 时间复杂度:O(n^2)
    • 空间复杂度: O(1)
const twoSum = function(nums, target) {
    const result = []
    nums.some((num1,  first)=>{
      return nums.some( (num2, second)=>{
          if( idx !== idenx && (one + two) === target  ){
              result.push(idenx, idx)
              return true
          }
      }  )
   })
   return result
};

创建hash表

  • 解题思路:
    • a. 第一种思路第一层遍历取出第一个数,第二层遍历取出第二个数,接下来的思路主要是如何去除两层循环,改成一层循环。
    • b.因为题目明确表示只会有一个正确答案,意味着不会有重复的数字,所以创建hash表,取数组值作为key,下标作为值
    • c.遍历数组,取target-i作为键查询hash中是否包含这个值,包含就取target-i对应值与当前遍历取得的索引作为结果返回
  • 复杂度
    • 时间复杂度:O(n)
    • 空间复杂度: O(n)
const twoSum = function(nums, target) {
    const result = []
    const hashmap =  nums.reduce( (map, i, idx)=> {
        map[i] = idx
        return map
    }, {} )
    nums.some( (i,second)=>{
        const first = hashmap[target -i]
        if( first !== undefined && first!== second){
            result.push(first,  second )
            return true
        }
    })
    return result
};
  • 进一步优化
    • 可以在第一个循环中直接判断目标值与当前值之差是否已存在于hashmap中
    const twoSum = function(nums, target) {
      const result = []
      const hashmap = {}
      nums.some( (i , second)=> {
           const first = hashmap[target -i]
      	 if( first !== undefined ){
          	    result.push(first,  second )
          	    return true
             }
          hashmap[i] = second
      })
      return result
    };
    

题目来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/tw…