add new solutions
This commit is contained in:
parent
0c73608ce5
commit
d798d5e8c9
19 changed files with 661 additions and 4 deletions
35
solutions/0/q2/solution.go
Normal file
35
solutions/0/q2/solution.go
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
package q2
|
||||
|
||||
type ListNode struct {
|
||||
Val int
|
||||
Next *ListNode
|
||||
}
|
||||
|
||||
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
|
||||
retRoot := &ListNode{}
|
||||
|
||||
p := retRoot
|
||||
carry := 0
|
||||
for l1 != nil || l2 != nil {
|
||||
val := carry
|
||||
if l1 != nil {
|
||||
val += l1.Val
|
||||
l1 = l1.Next
|
||||
}
|
||||
if l2 != nil {
|
||||
val += l2.Val
|
||||
l2 = l2.Next
|
||||
}
|
||||
|
||||
carry, val = val/10, val%10
|
||||
node := &ListNode{Val: val}
|
||||
p.Next = node
|
||||
p = node
|
||||
}
|
||||
if carry > 0 {
|
||||
p.Next = &ListNode{Val: carry}
|
||||
}
|
||||
return retRoot.Next
|
||||
}
|
||||
|
||||
var _ = addTwoNumbers
|
||||
36
solutions/0/q72/solution.go
Normal file
36
solutions/0/q72/solution.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package q72
|
||||
|
||||
func make2d[T any](rows, cols int) [][]T {
|
||||
alloc := make([]T, rows*cols)
|
||||
ret := make([][]T, rows)
|
||||
for i := range ret {
|
||||
ret[i] = alloc[cols*i : cols*(i+1)]
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func minDistance(word1 string, word2 string) int {
|
||||
minDists := make2d[int](len(word1)+1, len(word2)+1)
|
||||
|
||||
for i1 := range len(word1) {
|
||||
minDists[i1+1][0] = i1 + 1
|
||||
}
|
||||
for i2 := range len(word2) {
|
||||
minDists[0][i2+1] = i2 + 1
|
||||
}
|
||||
|
||||
for i1 := 1; i1 <= len(word1); i1++ {
|
||||
for i2 := 1; i2 <= len(word2); i2++ {
|
||||
if word1[i1-1] == word2[i2-1] {
|
||||
minDists[i1][i2] = minDists[i1-1][i2-1]
|
||||
} else {
|
||||
minDists[i1][i2] = min(
|
||||
minDists[i1-1][i2], minDists[i1][i2-1], minDists[i1-1][i2-1],
|
||||
) + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return minDists[len(word1)][len(word2)]
|
||||
}
|
||||
|
||||
var _ = minDistance
|
||||
23
solutions/0/q74/solution.go
Normal file
23
solutions/0/q74/solution.go
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
package q74
|
||||
|
||||
func searchMatrix(matrix [][]int, target int) bool {
|
||||
w, h := len(matrix[0]), len(matrix)
|
||||
idx := func(i int) (int, int) { return i / w, i % w }
|
||||
|
||||
l, r := 0, w*h
|
||||
for l < r {
|
||||
m := (l + r) / 2
|
||||
row, col := idx(m)
|
||||
switch {
|
||||
case matrix[row][col] == target:
|
||||
return true
|
||||
case matrix[row][col] < target:
|
||||
l = m + 1
|
||||
default:
|
||||
r = m
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var _ = searchMatrix
|
||||
Loading…
Add table
Add a link
Reference in a new issue