add new solutions

This commit is contained in:
kanna5 2025-12-29 12:16:39 +09:00
parent 59b71480d4
commit 71189b61cf
Signed by: kkyy
GPG key ID: 06332F3965E9B0CF
8 changed files with 200 additions and 0 deletions

View file

@ -0,0 +1,29 @@
package q202
type void struct{}
func next(n int) int {
ret := 0
for n > 0 {
digit := n % 10
n /= 10
ret += digit * digit
}
return ret
}
func isHappy(n int) bool {
seen := map[int]void{n: {}}
for {
n = next(n)
if n == 1 {
return true
}
if _, ok := seen[n]; ok {
return false
}
seen[n] = void{}
}
}
var _ = isHappy

View file

@ -0,0 +1,37 @@
package q222
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func count(node *TreeNode, depth int, maxDepth, mdFill *int) bool {
if node == nil {
return false
}
if node.Left == nil && node.Right == nil { // leaf
switch {
case depth == *maxDepth:
*mdFill++
case depth > *maxDepth:
*maxDepth = depth
*mdFill = 1
case depth < *maxDepth:
return true
}
}
return count(node.Left, depth+1, maxDepth, mdFill) ||
count(node.Right, depth+1, maxDepth, mdFill)
}
func countNodes(root *TreeNode) int {
maxdepth, mdFill := 0, 0
count(root, 1, &maxdepth, &mdFill)
if maxdepth == 0 {
return 0
}
return 1<<(maxdepth-1) - 1 + mdFill
}
var _ = countNodes

View file

@ -0,0 +1,17 @@
package q226
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
root.Left, root.Right = root.Right, root.Left
invertTree(root.Left)
invertTree(root.Right)
return root
}

View file

@ -0,0 +1,21 @@
package q242
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
cnt := map[rune]int{}
for _, r := range s {
cnt[r]++
}
for _, r := range t {
cnt[r]--
if cnt[r] < 0 {
return false
}
}
return true
}
var _ = isAnagram