Skip to content

Commit 286f0dd

Browse files
committed
practice on 20190907
1 parent 9b71cba commit 286f0dd

3 files changed

+52
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
object Solution {
2+
def sortedArrayToBST(nums: Array[Int]): TreeNode = {
3+
if (nums.isEmpty) null
4+
else{
5+
val pivot = nums.length / 2
6+
val root = new TreeNode(nums(pivot))
7+
root.left = sortedArrayToBST(nums.slice(0, pivot))
8+
root.right = sortedArrayToBST(nums.slice(pivot + 1, nums.length))
9+
root
10+
}
11+
}
12+
}

543_diameter_of_binary_tree.scala

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
object Solution {
2+
3+
def maxDepth(root: TreeNode): (Int, Int) = {
4+
if (root == null){
5+
(0, 0)
6+
}else{
7+
val maxLeft = maxDepth(root.left)
8+
val maxRight = maxDepth(root.right)
9+
(Math.max(maxLeft._1 + 1, maxRight._1 + 1), Math.max(Math.max(maxLeft._2, maxRight._2), maxLeft._1 + maxRight._1))
10+
}
11+
}
12+
13+
def diameterOfBinaryTree(root: TreeNode): Int = {
14+
maxDepth(root)._2
15+
}
16+
}

79_word_search.scala

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
object Solution {
2+
3+
def existRest(board: Array[Array[Char]], word: String, lastLoc: (Int, Int), locSet: Set[(Int, Int)]): Boolean = {
4+
if (word.isEmpty) true
5+
else{
6+
val candidates = Iterator(
7+
(lastLoc._1 + 1, lastLoc._2),
8+
(lastLoc._1 - 1, lastLoc._2),
9+
(lastLoc._1, lastLoc._2 + 1),
10+
(lastLoc._1, lastLoc._2 - 1)
11+
).filter(loc => (loc._1 >= 0 && loc._1 < board.length) && (loc._2 >= 0 && loc._2 < board(0).length) && (board(loc._1)(loc._2) == word.head) && !locSet.contains(loc))
12+
if (candidates.isEmpty) false else candidates.exists(loc => existRest(board, word.tail, loc, locSet + loc))
13+
}
14+
}
15+
16+
def exist(board: Array[Array[Char]], word: String): Boolean = {
17+
val indices = for{
18+
(a, i) <- board.iterator.zipWithIndex
19+
(c, j) <- a.iterator.zipWithIndex
20+
if( c == word.head )
21+
} yield i -> j
22+
if (indices.isEmpty) false else indices.exists(loc => existRest(board, word.tail, loc, Set(loc)))
23+
}
24+
}

0 commit comments

Comments
 (0)