add new solutions
This commit is contained in:
parent
59b71480d4
commit
71189b61cf
8 changed files with 200 additions and 0 deletions
29
solutions/2/q202/solution.go
Normal file
29
solutions/2/q202/solution.go
Normal 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
|
||||
37
solutions/2/q222/solution.go
Normal file
37
solutions/2/q222/solution.go
Normal 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
|
||||
17
solutions/2/q226/solution.go
Normal file
17
solutions/2/q226/solution.go
Normal 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
|
||||
}
|
||||
21
solutions/2/q242/solution.go
Normal file
21
solutions/2/q242/solution.go
Normal 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue