代码随想录算法训练营第5天 | lc242、lc349、lc202、lc1

发布时间 2023-12-03 22:15:19作者: geJoyo

(本合集全部为Go语言实现)

相关文章链接:242题解 349 202题解 1题解
相关视频链接:

Leetcode242

状态:秒了
实现过程中的难点:对于元素固定是小写字母或类似的情况,可以使用数组,因为元素最大数量是固定的

个人写法

func isAnagram(s string, t string) bool {
  if len(s) != len(t) {
    return false
  }
  note := make([]int, 26)
  for _, c := range s {
    note[int(c) - 'a']++
  }
  for _, c := range t {
    if (note[int(c) - 'a'] == 0) {
      return false
    }
    note[int(c) - 'a']--
  }
  return true
}

Leetcode349

状态:思路可以秒,过了
实现过程中的难点:遍历第一个数组,将其中的元素存到一个set中,再遍历第二个数组判断元素是否在set

个人写法

func intersection(nums1 []int, nums2 []int) []int {
  note := make(map[int]bool)
  res := make([]int, 0)
  for _, num := range nums1 {
    note[num] = true
  }
  for _, num := range nums2 {
    if v, ok := note[num]; ok && v {
      res = append(res, num)
      note[num] = false
    }
  }
  return res
}

Leetcode202

状态:秒了
实现过程中的难点:就是把每次的结果存下来,如果后续循环中发现已经存在,就说明值循环了,就不可能是快乐数了

个人写法

func isHappy(n int) bool {
  note := make(map[int]bool)
  for n != 1 {
    if _, ok := note[n]; ok {
      return false
    }
    note[n] = true
    curSum := 0
    for n != 0 {
      cur := n % 10
      curSum += cur * cur
      n /= 10
    }
    n = curSum
  }
  return true
}

Leetcode1

状态:稍微耗了一些时间
实现过程中的难点:代码中需要考虑到返回值中的两个下标不能相等

个人写法

看了题解之后的改进写法

func twoSum(nums []int, target int) []int {
  note := make(map[int]int)
  for i, num := range nums {
    if _, ok := note[target - num]; ok {
      return []int {i, note[target - num]}
    }
    note[num] = i
  }
  return []int {-1, -1}
}

今日收获

  • 复习了一下哈希表类型的题目整体的思路,一般来说都是使用哈希表来记录之前的状态来使后续过程使用到前边的状态
  • 这块涉及到了Go的Map等的使用,需要使用Map来模拟Set

学习时长:2小时左右