From 213f2d5969ca36bead1244416a292a0b422cb255 Mon Sep 17 00:00:00 2001 From: Kagura Date: Sun, 19 May 2024 15:13:23 +0800 Subject: [PATCH] Finish 10 this week --- src/Main.kt | 2 +- src/Test101.kt | 16 ++++++++++++++-- src/Test35.kt | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 3 deletions(-) create mode 100644 src/Test35.kt diff --git a/src/Main.kt b/src/Main.kt index 4bbd649..5696e57 100644 --- a/src/Main.kt +++ b/src/Main.kt @@ -1,4 +1,4 @@ fun main() { - val t = Test226() + val t = Test35() t.test() } \ No newline at end of file diff --git a/src/Test101.kt b/src/Test101.kt index 5c1752f..95a62a3 100644 --- a/src/Test101.kt +++ b/src/Test101.kt @@ -9,11 +9,23 @@ class Test101 { return true } - var pl = root.left - var pr = root.right + return isSame(root.left,root.right) + } + fun isSame(l: TreeNode?,r:TreeNode?):Boolean{ + if ((l==null && r!=null) || (r==null && l!=null)){ + return false + } + if (l==null && r==null){ + return true + } + if (l!!.`val`!=r!!.`val`){ + return false + } + + return isSame(l.left,r.right) && isSame(l.right,r.left) } } diff --git a/src/Test35.kt b/src/Test35.kt new file mode 100644 index 0000000..e7fc0c4 --- /dev/null +++ b/src/Test35.kt @@ -0,0 +1,49 @@ +class Test35 { + class Solution { + fun searchInsert(nums: IntArray, target: Int): Int { + if (nums.isEmpty()){ + return 0 + } + return binSearch(nums,0,nums.size,target) + } + + fun binSearch(nums: IntArray,low:Int,high:Int,target: Int):Int{ + if (low+1==high){ + if (target<=nums[low]){ + return low + } + return high + } + + if (target < nums[(low+high)/2]){ + return binSearch(nums,low,(low+high)/2,target) + }else if (target > nums[(low+high)/2]){ + return binSearch(nums,(low+high)/2,high,target) + } + return (low+high)/2 + } + } + + + fun test() { + val solution = Solution() + + val testCases = arrayOf( + Pair(intArrayOf(1, 3, 5, 6), 5) to 2, + Pair(intArrayOf(1, 3, 5, 6), 2) to 1, + Pair(intArrayOf(1, 3, 5, 6), 7) to 4, + Pair(intArrayOf(1, 3, 5, 6), 0) to 0, + Pair(intArrayOf(1), 1) to 0, + Pair(intArrayOf(), 1) to 0 + ) + + for ((input, expected) in testCases) { + val (nums, target) = input + val result = solution.searchInsert(nums, target) + println("Input: nums=${nums.contentToString()}, target=$target, Output: $result, Expected: $expected") + assert(result == expected) { "Test failed for input nums=${nums.contentToString()}, target=$target" } + } + + println("All tests passed!") + } +} \ No newline at end of file