dengxinyi 6 gadi atpakaļ
vecāks
revīzija
a7f12a0358
9 mainītis faili ar 263 papildinājumiem un 48 dzēšanām
  1. 69 0
      hard/25.go
  2. 0 7
      hard/32.go
  3. 8 10
      hard/4.go
  4. 13 17
      medium/103.go
  5. 23 0
      medium/105.go
  6. 34 3
      medium/95.go
  7. 26 0
      medium/96.go
  8. 63 0
      medium/98.go
  9. 27 11
      medium/helper.go

+ 69 - 0
hard/25.go

@@ -0,0 +1,69 @@
+package main
+
+import "fmt"
+
+/**
+ * Definition for singly-linked list.
+ * type ListNode struct {
+ *     Val int
+ *     Next *ListNode
+ * }
+ */
+func reverseKGroup(head *ListNode, k int) *ListNode {
+	if head == nil || head.Next == nil || k <= 1 {
+		return head
+	}
+	beforeBeg, beg, end, afterEnd := (*ListNode)(nil), head, head, head.Next
+	for end.Next != nil {
+		counter := 1
+		for end.Next != nil && counter < k {
+			end = end.Next
+			afterEnd = end.Next
+			counter++
+		}
+		if counter != k {
+			// Dont need to reverse
+			return head
+		}
+		// Reverse k node from beg to end
+		prev, curr, next := beforeBeg, beg, beg.Next
+		// Reverse all link between beforBeg & afterEnd
+		for i := 1; i < k; i++ {
+			prev = curr
+			curr = next
+			next = next.Next
+			curr.Next = prev
+		}
+		if beforeBeg == nil {
+			head = end
+		} else {
+			beforeBeg.Next = end
+		}
+		beg.Next = afterEnd
+		// Update anchor node
+		beforeBeg = beg
+		beg = beforeBeg.Next
+		end = beg
+		if end == nil {
+			return head
+		}
+		afterEnd = end.Next
+	}
+	return head
+}
+
+func main() {
+	// 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
+	n7 := ListNode{7, nil}
+	n6 := ListNode{6, &n7}
+	n5 := ListNode{5, &n6}
+	n4 := ListNode{4, &n5}
+	n3 := ListNode{3, &n4}
+	n2 := ListNode{2, &n3}
+	n1 := ListNode{1, &n2}
+	fmt.Println(list2str(&n1))
+	fmt.Println(list2str(reverseKGroup(&n1, 5)))
+	// 0
+	n0 := ListNode{0, nil}
+	fmt.Println(list2str(reverseKGroup(&n0, 1)))
+}

+ 0 - 7
hard/32.go

@@ -22,13 +22,6 @@ func longestValidParenthesesOld(s string) int {
 	return pair * 2
 }
 
-func maxInt(x, y int) int {
-	if x > y {
-		return x
-	}
-	return y
-}
-
 func longestValidParentheses(s string) int {
 	stack := []int{}
 	// max: longest length, beg: idx of last ')' before current stack

+ 8 - 10
hard/4.go

@@ -1,7 +1,5 @@
 package main
 
-import "fmt"
-
 // len(nums1) + len(nums2) != 0
 func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
 	// Use i, j to divide A, B into 2 parts, like
@@ -57,11 +55,11 @@ func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
 	return -1 // not found, useless
 }
 
-func main() {
-	nums1 := []int{1, 3}
-	nums2 := []int{2}
-	fmt.Println(findMedianSortedArrays(nums1, nums2))
-	nums3 := []int{}
-	nums4 := []int{1}
-	fmt.Println(findMedianSortedArrays(nums3, nums4))
-}
+// func main() {
+// 	nums1 := []int{1, 3}
+// 	nums2 := []int{2}
+// 	fmt.Println(findMedianSortedArrays(nums1, nums2))
+// 	nums3 := []int{}
+// 	nums4 := []int{1}
+// 	fmt.Println(findMedianSortedArrays(nums3, nums4))
+// }

+ 13 - 17
medium/103.go

@@ -1,9 +1,5 @@
 package main
 
-import (
-	"fmt"
-)
-
 /**
  * Definition for a binary tree node.
  * type TreeNode struct {
@@ -38,16 +34,16 @@ func zigzagLevelOrderHelper(root *TreeNode, level int, result *[][]int) {
 	}
 }
 
-func main() {
-	//        1
-	//       / \
-	//      2   3
-	//     / \
-	//    4   5
-	n5 := TreeNode{5, nil, nil}
-	n4 := TreeNode{4, nil, nil}
-	n3 := TreeNode{3, nil, nil}
-	n2 := TreeNode{2, &n4, &n5}
-	n1 := TreeNode{1, &n2, &n3}
-	fmt.Println(zigzagLevelOrder(&n1))
-}
+// func main() {
+// 	//        1
+// 	//       / \
+// 	//      2   3
+// 	//     / \
+// 	//    4   5
+// 	n5 := TreeNode{5, nil, nil}
+// 	n4 := TreeNode{4, nil, nil}
+// 	n3 := TreeNode{3, nil, nil}
+// 	n2 := TreeNode{2, &n4, &n5}
+// 	n1 := TreeNode{1, &n2, &n3}
+// 	fmt.Println(zigzagLevelOrder(&n1))
+// }

+ 23 - 0
medium/105.go

@@ -0,0 +1,23 @@
+package main
+
+/**
+ * Definition for a binary tree node.
+ * type TreeNode struct {
+ *     Val int
+ *     Left *TreeNode
+ *     Right *TreeNode
+ * }
+ */
+func buildTree(preorder []int, inorder []int) *TreeNode {
+	if len(preorder) == 0 || len(preorder) != len(inorder) {
+		return nil
+	}
+	root := TreeNode{preorder[0], nil, nil}
+	return &root
+}
+
+func main() {
+	printTree(buildTree(
+		[]int{3, 9, 20, 15, 7},
+		[]int{9, 3, 15, 20, 7}))
+}

+ 34 - 3
medium/95.go

@@ -9,11 +9,42 @@ package main
  * }
  */
 func generateTrees(n int) []*TreeNode {
-	result := []*TreeNode{}
+	if n == 0 {
+		return []*TreeNode{}
+	}
+	G := make([][]*TreeNode, n+1)
+	G[0] = []*TreeNode{nil}
+	G[1] = []*TreeNode{&TreeNode{1, nil, nil}}
+	for i := 2; i <= n; i++ {
+		G[i] = make([]*TreeNode, 0)
+		for j := 1; j <= i; j++ {
+			// G(i) = sum F(j, i)
+			// F(j, i) = G(j-1) * G(i-j)
+			for k := 0; k < len(G[j-1]); k++ {
+				for l := 0; l < len(G[i-j]); l++ {
+					right := copyAndAddBiTree(G[i-j][l], j)
+					root := &TreeNode{j, G[j-1][k], right}
+					G[i] = append(G[i], root)
+				}
+			}
+		}
+	}
+	return G[n]
+}
 
-	return result
+func copyAndAddBiTree(src *TreeNode, val int) *TreeNode {
+	if src == nil {
+		return nil
+	}
+	dst := TreeNode{src.Val + val, nil, nil}
+	dst.Left = copyAndAddBiTree(src.Left, val)
+	dst.Right = copyAndAddBiTree(src.Right, val)
+	return &dst
 }
 
 // func main() {
-// 	fmt.Println(generateTrees(3))
+// 	for _, root := range generateTrees(3) {
+// 		printTree(root)
+// 		println()
+// 	}
 // }

+ 26 - 0
medium/96.go

@@ -0,0 +1,26 @@
+package main
+
+// G(n) -> number of unique binary search tree of [1...n]
+// F(i, n) -> ... of [1...n] while i is root
+// G(n) = sum(F(i, n)), i ~ [1...n]
+// F(i, n) = G(i-1) * G(n-i)
+// So, G(n) = G(0) * G(n-1) + G(1) * G(n-2) + ... + G(n-1) * G(0)
+func numTrees(n int) int {
+	if n == 0 {
+		return 1
+	}
+	G := make([]int, n+1)
+	G[0], G[1] = 1, 1
+	for i := 2; i <= n; i++ {
+		for j := 1; j <= i; j++ {
+			G[i] += G[j-1] * G[i-j]
+		}
+	}
+	return G[n]
+}
+
+// func main() {
+// 	fmt.Println(numTrees(0))
+// 	fmt.Println(numTrees(1))
+// 	fmt.Println(numTrees(7))
+// }

+ 63 - 0
medium/98.go

@@ -0,0 +1,63 @@
+package main
+
+/**
+ * Definition for a binary tree node.
+ * type TreeNode struct {
+ *     Val int
+ *     Left *TreeNode
+ *     Right *TreeNode
+ * }
+ */
+func isValidBST(root *TreeNode) bool {
+	isValid, _, _ := isValidBSTRoot(root)
+	return isValid
+}
+
+func isValidBSTRoot(root *TreeNode) (isValid bool, min int, max int) {
+	if root == nil {
+		isValid = true
+		return // Do NOT rely on math.MaxInt32 or so
+	}
+	isValidL, minL, maxL := isValidBSTRoot(root.Left)
+	if root.Left == nil {
+		min = root.Val
+	} else {
+		if !isValidL || root.Val <= maxL {
+			return
+		}
+		min = minL
+	}
+	isValidR, minR, maxR := isValidBSTRoot(root.Right)
+	if root.Right == nil {
+		max = root.Val
+	} else {
+		if !isValidR || root.Val >= minR {
+			return
+		}
+		max = maxR
+	}
+	isValid = true
+	return
+}
+
+// func main() {
+// 	//    1
+// 	//   / \
+// 	// nil  2
+// 	//     / \
+// 	//    3  nil
+// 	n3 := TreeNode{3, nil, nil}
+// 	n2 := TreeNode{2, &n3, nil}
+// 	n1 := TreeNode{1, nil, &n2}
+// 	fmt.Println(isValidBST(&n1))
+// 	// nil
+// 	fmt.Println(isValidBST(nil))
+// 	// 2147483647
+// 	fmt.Println(isValidBST(&TreeNode{math.MaxInt32, nil, nil}))
+// 	//    1
+// 	//   / \
+// 	// nil  1
+// 	n6 := TreeNode{1, nil, nil}
+// 	n5 := TreeNode{1, nil, &n6}
+// 	fmt.Println(isValidBST(&n5))
+// }

+ 27 - 11
medium/helper.go

@@ -1,7 +1,7 @@
 package main
 
 import (
-	"fmt"
+	"strconv"
 )
 
 // ListNode ...
@@ -40,23 +40,39 @@ func minInt(x, y int) int {
 
 func list2str(head *ListNode) string {
 	curr := head
-	str := make([]rune, 0)
+	str := ""
 	for curr != nil {
-		str = append(str, rune(curr.Val+'0'))
+		str += strconv.FormatInt(int64(curr.Val), 10) + " "
 		curr = curr.Next
 	}
-	return string(str)
+	return str
 }
 
-func printTree(root *TreeNode) {
+func printTree(root *TreeNode) { // Level order traversal
 	if root == nil {
+		println("nil")
 		return
 	}
-	if root.Left != nil {
-		printTree(root.Left)
+	queue := make([]*TreeNode, 0) // Important!
+	queue = append(queue, root)
+	for len(queue) != 0 {
+		curr := queue[0]
+		queue = queue[1:] // Dequeue
+		if curr == nil {
+			print("nil ")
+			continue
+		}
+		print(curr.Val, " ")
+		if curr.Left != nil {
+			queue = append(queue, curr.Left)
+		} else if curr.Right != nil {
+			queue = append(queue, nil)
+		}
+		if curr.Right != nil {
+			queue = append(queue, curr.Right)
+		} else if curr.Left != nil {
+			queue = append(queue, nil)
+		}
 	}
-	if root.Right != nil {
-		printTree(root.Right)
-	}
-	fmt.Print(root.Val, " ")
+	println()
 }