This commit is contained in:
Kagura 2024-09-09 12:13:49 +08:00
parent 5c777cc6fb
commit 070b481895
3 changed files with 80 additions and 1 deletions

View file

@ -1,4 +1,4 @@
fun main() {
val t = Test125()
val t = Test977()
t.test()
}

41
src/Test88.kt Normal file
View file

@ -0,0 +1,41 @@
class Test88 {
class Solution {
fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int): Unit {
if (m == 0){
nums2.fold(0){ acc, i ->
nums1[acc] = i
acc +1
}
return
}
var mp = m-1
var np = n-1
while (mp != -1 && np != -1){
if (nums1[mp] >= nums2[np]){
nums1[mp + np +1] = nums1[mp]
mp --
}else{
nums1[mp + np +1] = nums2[np]
np --
}
}
while (np >= 0){
nums1[np] = nums2[np]
np--
}
}
}
fun test(){
val s = Solution()
val a11 = intArrayOf(1,2,3,0,0,0)
s.merge(a11,3, intArrayOf(4,5,6),3)
a11.forEach { print(it) }.also { println() }
val a21 = intArrayOf(2,0)
s.merge(a21,1, intArrayOf(1),1)
a21.forEach { print(it) }.also { println() }
}
}

38
src/Test977.kt Normal file
View file

@ -0,0 +1,38 @@
class Test977 {
class Solution {
fun sortedSquares(nums: IntArray): IntArray {
// -inf .. 0 <-l r-> 0.. +inf
var l = 0
while (l < nums.size && nums[l] < 0) {
l++
}
l --
var r = l + 1
var result = intArrayOf()
while (l >= 0 && r < nums.size) {
if (-nums[l] <= nums[r]) {
result += nums[l] * nums[l]
l--
} else {
result += nums[r] * nums[r]
r++
}
}
while (r < nums.size) {
result += nums[r] * nums[r]
r++
}
while (l >= 0) {
result += nums[l] * nums[l]
l--
}
return result
}
}
fun test(){
Solution().sortedSquares(intArrayOf(-4,-1,0,3,10)).forEach { print("$it,") }.also { println() }
Solution().sortedSquares(intArrayOf(-7,-3,2,3,11)).forEach { print("$it,") }.also { println() }
}
}