代码随想录训练营第五天 |

70 阅读1分钟

有效字母异位词

题目链接:有效字母异位词

  • 判断字符串出现的个数,可以用数组(参考本题),当然应该先排除长度不匹配
var isAnagram = function(s, t) {
  if(s.length !== t.length) return false
  // const res = new Array(26).fill(0)
  // const base = 'a'.charCodeAt()
  // for(const i of s) {
  //   res[i.charCodeAt() - base]++
  // }

  // for(const j of t) {
  //   if(!res[j.charCodeAt() - base]) return false
  //   res[j.charCodeAt() - base]--
  // }
  // return true

  const m = new Map()
  for(const i of s) {
    if(!m.has(i)) {
      m.set(i, 1)
    } else {
      m.set(i, (m.get(i) + 1))
    }
  }

  for(let j of t) {
    if(!m.get(j)) return false
    m.set(j, m.get(j) - 1)
  }

  return true
};

两个数组的交集

题目链接:两个数组的交集

  • 先对数组去重,然后用判断一个数组是否存在另一个数组的值
var intersection = function(nums1, nums2) {
    const s3 = Array.from(new Set(nums1)), s4 = Array.from(new Set(nums2))
    const res = []
    for(const i of s3) {
        if(s4.includes(i)) res.push(i)
    }
    return res
};

快乐数

题目链接:快乐数

var isHappy = function(n) {
    const get = (n) => {
        let sum = 0
        while(n) {
            let temp = n % 10
            sum += temp * temp
            n = Math.floor(n / 10)
        }
        return sum
    }

    const m = new Set()
    while(n !== 1) {
        if(m.has(n)) return false
        m.add(n) 
        n = get(n)
    }
    return true
};

两数之和

题目链接:两数之和

var twoSum = function(nums, target) {
    const m = new Map()
    for(let i = 0; i < nums.length; i++) {
        if(m.has(target - nums[i])) return [m.get(target - nums[i]), i]
        m.set(nums[i], i)
    }
};